简体   繁体   中英

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'

你可以这样做

key, value = hash.first

You can use Hash#flatten , which has been around since at least Ruby v1.9.3. Unlike Array#flatten , it does not flatten recursively.

hash = { foo: ['bar', 'boo'] }

foo, bar = hash.flatten
  #=> [:foo, ["bar", "boo"]] 

I have encountered situations where it was helpful to know that (since Ruby v1.9) a hash's keys will retain their order of insertion. That's unusual, however, so the asker is advised to review their code to see if a design that doesn't rely on key order might not be better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM