Class: DarrylJenks::Permutable
- Inherits:
-
Object
- Object
- DarrylJenks::Permutable
- Defined in:
- lib/darryl_jenks/permutable.rb
Instance Attribute Summary collapse
-
#key_string ⇒ Object
Returns the value of attribute key_string.
Instance Method Summary collapse
-
#each_permutation(permutable_key, substitution_value, options = {}) ⇒ Object
Computes the Permutations of a string.
-
#initialize(key_string = nil) ⇒ Permutable
constructor
Constructor can be initialized with the key_string to initialize off of.
Constructor Details
#initialize(key_string = nil) ⇒ Permutable
Constructor can be initialized with the key_string to initialize off of
8 9 10 |
# File 'lib/darryl_jenks/permutable.rb', line 8 def initialize( key_string = nil ) self.key_string = key_string end |
Instance Attribute Details
#key_string ⇒ Object
Returns the value of attribute key_string.
3 4 5 |
# File 'lib/darryl_jenks/permutable.rb', line 3 def key_string @key_string end |
Instance Method Details
#each_permutation(permutable_key, substitution_value, options = {}) ⇒ Object
Computes the Permutations of a string
Ex: key_string = “HELLO WORLD FIRST”
each_permutation(“ ”, “-”) dash_permutations = [ “HELLO-WORLD FIRST”, “HELLO-WORLD-FIRST”, “HELLO WORLD-FIRST” ]
The ‘permutable_key’ is the character/regex that should be used as the split mechanism to determine how many objects are in the collection to be “permed”
The ‘substitution_value’ is the character that should be used in the permutations of the string as the separator value
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/darryl_jenks/permutable.rb', line 26 def each_permutation(permutable_key, substitution_value, = {}) return unless self.key_string.index(permutable_key) permutations = [] split_tokens = self.key_string.split(permutable_key,-1) # At least a single permutation needs to be present number_of_permutations = [(split_tokens.size - 1), 1].max permutations_for(number_of_permutations).each do |permutation_pattern| permutation_string = "" copied_tokens = split_tokens.map(&:dup) permutation_pattern.each do |replace_split_token| permutation_string << copied_tokens.shift if replace_split_token permutation_string << substitution_value else permutation_string << ([:non_replace_substitution] || permutable_key) end end permutation_string << copied_tokens.shift unless copied_tokens.empty? permutations << permutation_string end if block_given? permutations.each do |permutation| yield permutation end else permutations.to_enum end end |