I’m reading through Why’s Poignant Guide to Ruby and I came upon this code example wherein he adds a class variable and an instance method to the String class. The idea is that, given a string of an alien name, like “Paij-Ree”, we could run something like
"Paij-ree".determine_significance # returns "Personal AM"
Here is the code:
class String
@@syllables = [
{ 'Paij' => 'Personal',
'Gonk' => 'Business',
'Blon' => 'Slave',
'Stro' => 'Master',
'Wert' => 'Father',
'Onnn' => 'Mother' },
{ 'ree' => 'AM',
'plo' => 'PM' }
]
# a method to determine what a certain
# name of his means
def determine_significance
parts = self.split( '-' )
syllables = @@syllables.dup
signif = parts.collect do |p|
syllables.shift[p]
end
signif.join( ' ' )
end
end
My question: What is going on in the collect block where there are square brackets after the Array#shift method? I’ve only been able to find examples where it is used like this:
letters = ['a','b','c']
letters.shift # returns "a"
What’s going on here?
syllables.shift[p]
It’s doing exactly that.
@@syllablesis an array of hashes, so it shifts the first value out of the array, which is a hash. Then it accesses it using the split string as the key.self.split( '-' )returns a string array and that is mapped over withcollectto replace it with the value in the hash.The important part is that the array is duplicated to avoid destroying the original
@@syllablesso you can shift the duplicate.