Argus9 Argus9 - 5 months ago 26
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]


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


You can do this

key, value = hash.first