我无法想出一个很好的方法来访问splat运算符中提供的键名称的多维哈希 - 任何建议?
示例:我喜欢哈希
{
'key' => 'value',
'some' => {
'other' => {
'key' => 'othervalue'
}
}
}
Run Code Online (Sandbox Code Playgroud)
和一个功能定义 def foo(*args)
我想回到foo('key') value和foo('some','other','key') othervalue.所有我能想到的都是相当长而丑陋的循环与很多nil?检查,并且我确定我错过了一个更好的红宝石方式来做这个好又短.任何提示都表示赞赏.
使用Patrick下面的回复,我想到了
def foo(hash, *args)
keys.reduce(hash, :fetch)
end
Run Code Online (Sandbox Code Playgroud)
这是我期望的那样.谢谢!
在其他一些语言中,这被称为get_in例如Clojure和Elixir.这是Ruby中的功能实现:
class Hash
def get_in(*keys)
keys.reduce(self, :fetch)
end
end
Run Code Online (Sandbox Code Playgroud)
用法:
h = {
'key' => 'value',
'some' => {
'other' => {
'key' => 'othervalue'
}
}
}
h.get_in 'some'
#=> {
# "other" => {
# "key" => "othervalue"
# }
# }
h.get_in 'some', 'other'
#=> {
# "key" => "othervalue"
# }
h.get_in 'some', 'other', 'key'
#=> "othervalue"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |