Class: Wordlist::Modifiers::Sub

Inherits:
Modifier
  • Object
show all
Defined in:
lib/wordlist/modifiers/sub.rb

Overview

Lazily calls String#sub on every word in the wordlist.

Since:

  • 1.0.0

Direct Known Subclasses

Gsub, Mutate

Instance Attribute Summary collapse

Attributes inherited from Modifier

#wordlist

Instance Method Summary collapse

Constructor Details

#initialize(wordlist, pattern, replace = nil) {|match| ... } ⇒ Sub

Initializes the String#sub modifier.

Parameters:

  • pattern (Regexp, String)

    The pattern to replace.

  • replace (String, Hash, nil) (defaults to: nil)

    The characters or character range to use as the replacement.

Yields:

  • (match)

    The given block will be call to replace the matched substring, if replace is nil.

Yield Parameters:

  • match (String)

    A matched substring.

Raises:

  • (TypeError)

    The replace value was not a String, Hash, or nil.

Since:

  • 1.0.0



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/wordlist/modifiers/sub.rb', line 47

def initialize(wordlist,pattern,replace=nil,&block)
  super(wordlist)

  @pattern = pattern
  @replace = case replace
             when String, Hash, nil then replace
             else
               raise(TypeError,"no implicit conversion of #{replace.class} to String")
             end
  @block   = block
end

Instance Attribute Details

#blockProc? (readonly)

The optional block to call when replacing matched substrings.

Returns:

  • (Proc, nil)

Since:

  • 1.0.0



26
27
28
# File 'lib/wordlist/modifiers/sub.rb', line 26

def block
  @block
end

#patternRegexp, String (readonly)

The pattern to substitute.

Returns:

  • (Regexp, String)

Since:

  • 1.0.0



16
17
18
# File 'lib/wordlist/modifiers/sub.rb', line 16

def pattern
  @pattern
end

#replaceString, Hash{String => String, nil} (readonly)

The replacement String or map of Strings.

Returns:

  • (String, Hash{String => String, nil})

Since:

  • 1.0.0



21
22
23
# File 'lib/wordlist/modifiers/sub.rb', line 21

def replace
  @replace
end

Instance Method Details

#each {|word| ... } ⇒ Enumerator

Enumerates over every subed word in the wordlist.

Examples:

wordlist = Wordlist::Words["foo", "bar", "baz"]
wordlist.sub(/o/, '0').each do |word|
  puts word
end
# f0o
# bar
# baz

Yields:

  • (word)

    The given block will be passed each subed word.

Yield Parameters:

  • word (String)

    A subed word.

Returns:

  • (Enumerator)

    If no block is given, an Enumerator object will be returned.

Since:

  • 1.0.0



82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/wordlist/modifiers/sub.rb', line 82

def each
  return enum_for(__method__) unless block_given?

  if @replace
    @wordlist.each do |word|
      yield word.sub(@pattern,@replace)
    end
  else
    @wordlist.each do |word|
      yield word.sub(@pattern,&block)
    end
  end
end