Argus9 Argus9 - 1 month ago 5
Ruby Question

Split a single-pair Hash into its key and value?

Does Ruby include a method that lets you take a single-pair Hash (example:

{:foo => 'bar'}
) and separate the key and value into two variables? I've written a small method to do this but I don't want to be redundant if Ruby can already do it. Back-of-napkin code provided below.

def split_hash hash
key = hash.keys.first
key, hash[key]
end


Usage:

hash = {:foo => 'bar'}
foo, bar = split_hash hash
# Expected: foo = :foo, bar = 'bar'

Answer

You can do this

key, value = hash.first
Comments