Ross Bamford
1/11/2006 9:23:00 AM
On Wed, 11 Jan 2006 04:31:52 -0000, Will <wrbriggs@gmail.com> wrote:
> 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.
>
Stupid questions (i.e. the asking of) are my speciality these days ( :( )
and this doesn't seem to be a particularly dumb one to me :) You are
right though about a more elegant way to do it:
h = Hash['blue', 34, 'red', 31, 'green', 32] # => {"green"=>32,
"blue"=>34, "red"=>31}
a = [1, 'one', 2, 'two', 3, 'three'] # => [1, "one", 2, "two", 3,
"three"]
h = Hash[*a] # => {1=>"one", 2=>"two", 3=>"three"}
(Notice the * on the second form)
Cheers,
--
Ross Bamford - rosco@roscopeco.remove.co.uk