W
Will
Hi folks, I know that this is a really simple question, and there must
be many ways to do it in Ruby... but what I'm looking for is an
elegant way to take a collection of objects and create a hash mapping
one attribute of the object as the key and the other as the value. So
far what I am doing is this:
objects = some_method_to_return_collect( method_params )
myHash = Hash.new
@objects.each do |object|
myHash[ object.key ] = object.value
end
I played around with doing something like:
@myHash = objects.map do |object| [ object.key => object.value ] end
But that returns an array of single-value hashes, which is not exactly
what I am trying to do.
I know this is a stupid question, and probably pointless because I do
know ways to do it, but I would really like the know the Ruby Way to do
this. Ruby seems so given to elegant code that my code above really
bugs me for some reason.
Thanks all!
-Will
be many ways to do it in Ruby... but what I'm looking for is an
elegant way to take a collection of objects and create a hash mapping
one attribute of the object as the key and the other as the value. So
far what I am doing is this:
objects = some_method_to_return_collect( method_params )
myHash = Hash.new
@objects.each do |object|
myHash[ object.key ] = object.value
end
I played around with doing something like:
@myHash = objects.map do |object| [ object.key => object.value ] end
But that returns an array of single-value hashes, which is not exactly
what I am trying to do.
I know this is a stupid question, and probably pointless because I do
know ways to do it, but I would really like the know the Ruby Way to do
this. Ruby seems so given to elegant code that my code above really
bugs me for some reason.
Thanks all!
-Will