hash = {}
array.each { |key| hash[key] = func(key) }
Refactorings
No refactoring yet !
Krzysztof Wilczynski
August 16, 2010, August 16, 2010 12:19, permalink
Try this one ...
def f(i)
i ** 2
end
array = [1, 2, 3]
hash = Hash[array.collect { |i| [i, f(i)] }]
Krzysztof Wilczynski
August 16, 2010, August 16, 2010 12:22, permalink
Also, for MRI/REE version pre 1.8.7 you have to splat ...
hash = Hash[*array.collect { |i| [i, f(i)] }.flatten]
Adam
August 16, 2010, August 16, 2010 15:02, permalink
array.inject({}) { |hash,key| hash.merge(key => func(key)) }
Martin Plöger
August 16, 2010, August 16, 2010 17:39, permalink
merge! is more efficient than merge (creates copies of the old hash). Just a tiny change...
array.inject({}) { |hash, key| hash.merge! key => func(key) }
Adam
August 16, 2010, August 16, 2010 23:35, permalink
True, but Hash#update is even more efficient than merge!, if efficiencies are your concern.
array.inject({}) { |hash,key| hash.update(key => func(key)) }
Serguei Filimonov
August 17, 2010, August 17, 2010 22:23, permalink
I don'k now about idiomatic, but I feel that creating a hash from 2 arguments: keys and values -- is the most clear way. So you'll need to monkey patch Hash or something for this.
This is by far not as terse as the other ways, but probably easier to read in my opinion
#put in hash_extensions.rb in lib somewhere
def Hash.from_keys_and_values(keys,values)
hash = {}
keys.each_with_index do |key, i|
hash[key] = values[i]
end
hash
end
#in your code
array = [1,2,3,4,5]
squares = array.collect{|i| i**2}
hash = Hash.from_keys_and_values(array, squares)
Can you make this code more idiomatic?