ave
ave

Reputation: 19443

Easy way to extract key-value from hash

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

Answers (3)

Darek Nędza
Darek Nędza

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

hirolau
hirolau

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

sawa
sawa

Reputation: 168101

k, v = {a: :b}.first
k # => :a
v # => :b

Upvotes: 4

Related Questions