M
Mikel Lindsaar
class Fruit
attr_accessor :name,
rice
def initialize(args)
@name = args[:name]
@price = args[
rice]
end
end
array = [ Fruit.new
name => "apple",
rice => 2),
Fruit.new
name => "grape",
rice => 20),
Fruit.new
name => "pear",
rice => 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
attr_accessor :name,
def initialize(args)
@name = args[:name]
@price = args[
end
end
array = [ Fruit.new
Fruit.new
Fruit.new
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