Create an array from a hash that includes key and value

Hello there, I have the hash:

@hash = {“a”=>“1”, “b”=>“2”, “c”=>“3”}

And I need to create an array:

@array = [ [‘a’,‘1’],[‘b’,‘2’],[‘c’,‘3’] ]

How do I do that?

Paco Reyes

@hash.to_a

Hi –

On Fri, 18 Jul 2008, paco.onrails wrote:

Hello there, I have the hash:

@hash = {“a”=>“1”, “b”=>“2”, “c”=>“3”}

And I need to create an array:

@array = [ [‘a’,‘1’],[‘b’,‘2’],[‘c’,‘3’] ]

How do I do that?

@hash.to_a

David


Rails training from David A. Black and Ruby Power and Light:
Intro to Ruby on Rails July 21-24 Edison, NJ
Advancing With Rails August 18-21 Edison, NJ
See http://www.rubypal.com for details and updates!

Rob,
Could I ride this thread with a short variation? I have a zillion
dropdowns in my project that ask users what code they should choose.
As a ficticious example they’d be asked what day of the week ( 1 -
Sunday, 2 - Monday, 3 - Tuesday, etc. )
I’d like to simply create this as an array and pass it to my
collection_select helper. This would save me having to create another
model and migration.
What throws me is that the first member of an array has a zero 0 key
and I want it to be one 1.
Could someone show me the simple way to load an array with key - value
combinations that starts with one 1.
Thank you,
Kathleen

On Jul 18, 11:55 am, Rob B. [email protected]

On Jul 18, 2008, at 11:19 AM, paco.onrails wrote:

Paco Reyes
Either:
@array = @hash.to_a

or:
@array = @hash.to_a.sort

depending on whether the order matters. A Hash (in Ruby 1.8.6 and
earlier) is inherently unordered and the conversion to an array gives
elements in the same order that @hash.each would yield them.

-Rob

Rob B. http://agileconsultingllc.com
[email protected]