Argus9 Argus9 - 1 year ago 65
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'

Answer Source

You can do this

key, value = hash.first
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download