Convenient way to get many hash elements at once.

R

Ron M

If I have a hash table with a bunch of fields; and I want to
extract a subset of them, kinda like "@a_hashtable{'a','c'}"
in perl, is there a nice way of doing so?
I was hoping something like this would work...

h={'first name'=>'John', 'last name'=>'Doe', 'birthday'=>'1970-01-01', 'height'=>'5 foot'}

h['first name','last name'] # hoping for ['John','Doe'] as a result.

but it gave me

ArgumentError: wrong number of arguments (2 for 1)
from (irb):126:in `[]'
from (irb):126
from ^C:0

I suppose
['first name','last name'].map{|x| h[x]}
does what I want; but it surely isn't as readable as
h['first name','last name']

If there's no cleaner way of doing this; would it be a reasonably
Ruby 2.0 request to allow Hash#[] to take multiple arguments and
return multiple return values for each of the arguments?
 
S

Simon Strandgaard

If I have a hash table with a bunch of fields; and I want to
extract a subset of them, kinda like "@a_hashtable{'a','c'}"
in perl, is there a nice way of doing so?
I was hoping something like this would work...

h=3D{'first name'=3D>'John', 'last name'=3D>'Doe', 'birthday'=3D>'1970-= 01-01', 'height'=3D>'5 foot'}

h['first name','last name'] # hoping for ['John','Doe'] as a result.

h.values_at('first name', 'last name')
#=3D> ["John", "Doe"]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top