Af19cd0c0141bf7d6b42516706eb1d1d

Can you make this code more idiomatic?

hash = {}
array.each { |key| hash[key] = func(key) }

Refactorings

No refactoring yet !

9dc2fe52cbc7a4f42b54d056e470efea

Krzysztof Wilczynski

August 16, 2010, August 16, 2010 12:19, permalink

2 ratings. Login to rate!

Try this one ...

def f(i)
  i ** 2
end

array = [1, 2, 3]

hash = Hash[array.collect { |i| [i, f(i)] }]
9dc2fe52cbc7a4f42b54d056e470efea

Krzysztof Wilczynski

August 16, 2010, August 16, 2010 12:22, permalink

No rating. Login to rate!

Also, for MRI/REE version pre 1.8.7 you have to splat ...

hash = Hash[*array.collect { |i| [i, f(i)] }.flatten]
A8d3f35baafdaea851914b17dae9e1fc

Adam

August 16, 2010, August 16, 2010 15:02, permalink

No rating. Login to rate!
array.inject({}) { |hash,key| hash.merge(key => func(key)) }
E8f0d6e9bc8bca695b3c5bdf75cdcc03

Martin Plöger

August 16, 2010, August 16, 2010 17:39, permalink

No rating. Login to rate!

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) }
A8d3f35baafdaea851914b17dae9e1fc

Adam

August 16, 2010, August 16, 2010 23:35, permalink

No rating. Login to rate!

True, but Hash#update is even more efficient than merge!, if efficiencies are your concern.

array.inject({}) { |hash,key| hash.update(key => func(key)) }
D0180794e9d81d80e37ff5962032dca8

Serguei Filimonov

August 17, 2010, August 17, 2010 22:23, permalink

No rating. Login to rate!

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)

Your refactoring





Format Copy from initial code

or Cancel