Class: Hyde::Pattern

Inherits:
Object
  • Object
show all
Defined in:
lib/hyde/pattern_matching.rb

Overview

Delegate class for all available patterns. Picks appropriate pattern based on contents.

Instance Method Summary collapse

Constructor Details

#initialize(pattern) ⇒ Pattern

Returns a new instance of Pattern.

Parameters:

  • pattern (Object)

    object to generate pattern from



16
17
18
19
# File 'lib/hyde/pattern_matching.rb', line 16

def initialize(pattern)
  @pattern = patternify(pattern)
  @static = @pattern.is_a? String
end

Instance Method Details

#match(input) ⇒ Array(String,Array,Hash), FalseClass

Match the string and assign matches to parameters. Returns:

  • Unmatched part of a string
  • Unnamed parameters
  • Named parameters

Parameters:

  • input (String)

    String to match

Returns:

  • (Array(String,Array,Hash))
  • (FalseClass)

    if input doesn't match pattern



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/hyde/pattern_matching.rb', line 35

def match(input)
  if @pattern.is_a? String
    input = Hyde::PatternMatching.canonicalize(input)
    if input.start_with?(@pattern)
      [input.delete_prefix(@pattern), [], {}]
    else
      false
    end
  else
    @pattern.match(input)
  end
end

#match?(input) ⇒ Boolean

Test if a string can be matched. Lighter version of match that doesn't assign any variables.

Parameters:

  • input (String)

    String to match

Returns:

  • (Boolean)


52
53
54
55
56
57
58
# File 'lib/hyde/pattern_matching.rb', line 52

def match?(input)
  if @pattern.is_a? String
    Hyde::PatternMatching.canonicalize(input).start_with? @pattern
  else
    @pattern.match?(input)
  end
end

#static?Boolean

Checks if pattern object is static (is a simple String pattern).

Returns:

  • (Boolean)


22
23
24
# File 'lib/hyde/pattern_matching.rb', line 22

def static?
  @static
end