Reputation: 19443
Is there some nice way to extract key and value from a hash?
My first approach was:
a = {:a => :b}
a.keys.first # => :a
a.values.first # => :b
But it looks a bit clumsy, so I came up with this:
k, v = {:a => :b}.to_a.flatten
k # => :a
v # => :b
Are there some other ways?
Upvotes: 1
Views: 239
Reputation: 1420
Here is some more, but, the same as hirolau, I don't think it's better than sawa's answer.
each_pair
, each
and more methods, returns Enumerator
object. With this you can get next
value with... next
:
h.each_pair.next
# [:a, :b]
h.each.next
# => [:a, :b]
And entries
return array of arrays:
a, b = h.entries[0]
or other way, using ruby's pattern matching:
((a,b)) = h.entries
Upvotes: 1
Reputation: 13901
Here are two more ways, but I do not think they are nicer than sawa's answer:
key, val = *a.flatten
key, val = [*a][0]
Or, if you do not care about the original hash anymore:
key, val = a.shift
Upvotes: 2