J
josefK
I encountered this added method to Array (I don't recall
the author - sorry ,)
It converts an Array to a Hash by providing a block to compute the
values given the array elements as keys:
class Array
def to_h(&block)
Hash[*self.collect{|v| [v,block.call(v)]}.flatten]
end
end
#exp
a=[1,2,3]
h=a.to_h{|e| 2**e}
h.each{|k,v| puts "key=#{k} val=#{v}"}
#->key=1 val=2 key=2 val=4 key=3 val=8
Without the '*' on self it generates an error:
array2hash.rb:3:in `[]': odd number of arguments for Hash (ArgumentError)
from array2hash.rb:3:in `to_h'
from array2hash.rb:8
What does the '*' do to correct the error?
Does it push self up a level to Array somehow?
Does this notation generalize?
Thanks,
Mark
the author - sorry ,)
It converts an Array to a Hash by providing a block to compute the
values given the array elements as keys:
class Array
def to_h(&block)
Hash[*self.collect{|v| [v,block.call(v)]}.flatten]
end
end
#exp
a=[1,2,3]
h=a.to_h{|e| 2**e}
h.each{|k,v| puts "key=#{k} val=#{v}"}
#->key=1 val=2 key=2 val=4 key=3 val=8
Without the '*' on self it generates an error:
array2hash.rb:3:in `[]': odd number of arguments for Hash (ArgumentError)
from array2hash.rb:3:in `to_h'
from array2hash.rb:8
What does the '*' do to correct the error?
Does it push self up a level to Array somehow?
Does this notation generalize?
Thanks,
Mark