Hash#to_a method not performing

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 logger.info('array ' + ha.inspect)

development.log :- hash {"a"=>100, "c"=>300, "d"=>400} array {"a"=>100, "c"=>300, "d"=>400}

IRB does not show this problem

Ruby Version 1.8.6

Any ideas?

Peter

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