Argus9 Argus9 - 6 months ago 29
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