class Fruit
attr_accessor :name, :price
def initialize(args)
@name = args[:name]
@price = args[:price]
end
end
array = [ Fruit.new(:name => "apple", :price => 2),
Fruit.new(:name => "grape", :price => 20),
Fruit.new(:name => "pear", :price => 200) ]
hash = Hash.new
array.each do |obj|
hash.merge!({obj.name => obj.price})
end
hash.inspect # => "{\"grape\"=>20, \"apple\"=>2, \"pear\"=>200}"
The "hash = {} / hash.merge!" thing bugs me... what is the better way?
Mikel