Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Convenient way to get many hash elements at once.

15 views
Skip to first unread message

Ron M

unread,
Oct 17, 2005, 5:18:21 AM10/17/05
to
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?

Simon Strandgaard

unread,
Oct 17, 2005, 5:23:28 AM10/17/05
to
On 10/17/05, Ron M <rm_r...@cheapcomplexdevices.com> wrote:
> 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.
>

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

--
Simon Strandgaard


0 new messages