People used to do it this way:
hash = {}
input.each do |item|
hash[item] = process(item)
end
hash
: (
Two solutions:
# from http://www.h6.dion.ne.jp/~machan/misc/FPwithRuby.html
module Enumerable
def mash(&block)
self.inject({}) do |output, item|
key, value = block_given? ? yield(item) : item
output.merge(key => value)
end
end
end
module Enumerable
def mash(&block)
Hash[self.map do |item|
if block_given?
yield(item)
else
nil
end
end]
end
end
syntax
pry > ["I", "love", "Ruby"].mash { |w| [w, w.size] }
=> {"I"=>1, "love"=>4, "Ruby"=>4}
Which one do you prefer?