什么是在任意深度访问嵌套哈希值的最红宝石方式? [英] What is the most ruby-ish way of accessing nested hash values at arbitrary depths?
问题描述
$ b
AppConfig = {
'service' => {
'key'=> 'abcdefg',
'secret'=> 'secret_abcdefg'
},
'other'=> {
'service'=> {
'key'=> 'cred_abcdefg',
'secret'=> 'cred_secret_abcdefg'
}
}
}
我需要一个函数在某些情况下返回服务/密钥,在其他情况下返回其他/服务/密钥。一个简单的方法是传入哈希和一个键数组,如下所示:
$ b
def val_for(hash,array_of_key_names)
h = hash
array_of_key_names.each {| k | h = h [k]}
h
end
在'cred_secret_abcdefg'中:
$ b
val_for(AppConfig,%w [other service secret])
好像应该有比我在val_for()中写的更好的方法。
def val_for(hash,keys)
keys .reduce(hash){| h,key | h [key]}
end
如果某个中间键不是找到。还要注意,这完全等同于 keys.reduce(hash,:[])
,但这可能会让一些读者感到困惑,我会使用该块。 p>
Given a hash such as:
AppConfig = {
'service' => {
'key' => 'abcdefg',
'secret' => 'secret_abcdefg'
},
'other' => {
'service' => {
'key' => 'cred_abcdefg',
'secret' => 'cred_secret_abcdefg'
}
}
}
I need a function to return service/key in some cases and other/service/key in other cases. A straightforward way is to pass in the hash and an array of keys, like so:
def val_for(hash, array_of_key_names)
h = hash
array_of_key_names.each { |k| h = h[k] }
h
end
So that this call results in 'cred_secret_abcdefg':
val_for(AppConfig, %w[other service secret])
It seems like there should be a better way than what I've written in val_for().
def val_for(hash, keys)
keys.reduce(hash) { |h, key| h[key] }
end
This will raise an exception if some intermediate key is not found. Note also that this is completely equivalent to keys.reduce(hash, :[])
, but this may very well confuse some readers, I'd use the block.
这篇关于什么是在任意深度访问嵌套哈希值的最红宝石方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!