将单对Hash拆分为其键和值?

Arg*_*us9 2 ruby

Ruby是否包含一个方法,允许您使用单对Hash(示例:) {:foo => 'bar'}并将键和值分成两个变量?我写了一个小方法来做到这一点,但如果Ruby已经可以做到,我不想多余.下面提供的餐巾纸代码.

def split_hash hash
    key = hash.keys.first
    key, hash[key]
end
Run Code Online (Sandbox Code Playgroud)

用法:

hash = {:foo => 'bar'}
foo, bar = split_hash hash
# Expected: foo = :foo, bar = 'bar'
Run Code Online (Sandbox Code Playgroud)

Ser*_*sev 5

你可以这样做

key, value = hash.first
Run Code Online (Sandbox Code Playgroud)