On 10/31/07, Peter <peter.cutting-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:>
> Hi
> I need to turn a hash into an array. The method .to_a should do it.
> unfortunately not
>
> ha = { "c" => 300, "a" => 100, "d"
=> 400, "c" => 300 }
> logger.info(''hash '' + ha.inspect)
> ha.to_a
This creates a new object which is the result of sending to_a to the
object referenced by ha, then throws it away.> logger.info(''array '' + ha.inspect)
ha is still the original array.
> development.log :-
> hash {"a"=>100, "c"=>300, "d"=>400}
> array {"a"=>100, "c"=>300, "d"=>400}
>
> IRB does not show this problem
Only because you didn''t ask it the right questions:
irb(main):001:0> ha = { "c" => 300, "a" => 100,
"d" => 400, "c" => 300 }
=> {"a"=>100, "c"=>300, "d"=>400}
irb(main):002:0> ha.to_a
=> [["a", 100], ["c", 300], ["d", 400]]
irb(main):003:0> ha
=> {"a"=>100, "c"=>300, "d"=>400}
irb(main):004:0>
Since irb prints (actually it uses p) the value of each expression you
enter, you get to see the array created by line 2, before it''s garbage
collected. But line 3 shows that the binding of ha to the original
hash has not changed.
try something like this:
hash = { "c" => 300, "a" => 100, "d" =>
400, "c" => 300 }
logger.info(''hash '' + hash.inspect)
array = hash.to_a
logger.info(''array '' + array.inspect)
Don''t confuse variables with objects in Ruby.
http://talklikeaduck.denhaven2.com/articles/2006/09/13/on-variables-values-and-objects
--
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denhaven2.com/
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---