使用地址数组的ruby访问链
假设我有:使用地址数组的ruby访问链,ruby,hash,Ruby,Hash,假设我有: a = { b:1 , c: { d:2, e:3 } } address = [:c, :e] 我可以使用 a[ address[0] ][ address[1] ] 但这是不灵活的,我希望能够获取任意地址数组并对其进行哈希处理 有没有一种优雅的方法可以做到这一点,或者我需要编写一个递归方法?如果它接受数组,那就太好了。使用递归的方法: a = { b:1 , c: { d:2, e:3 } } address = [:c, :e] address.inject(a, :[])
a = { b:1 , c: { d:2, e:3 } }
address = [:c, :e]
我可以使用
a[ address[0] ][ address[1] ]
但这是不灵活的,我希望能够获取任意地址数组并对其进行哈希处理
有没有一种优雅的方法可以做到这一点,或者我需要编写一个递归方法?如果它接受数组,那就太好了。使用递归的方法:
a = { b:1 , c: { d:2, e:3 } }
address = [:c, :e]
address.inject(a, :[])
# => 3
def probe(h, address)
address.size==1 ? h[address.first] : probe(h[address.first], address[1..-1])
end
h = { b:1 , c: { d:2, e:3 } }
a = [:c, :e]
probe(h,a) #=> 3
或者,如果您愿意:
def probe(h, address)
begin
probe(h[address.first], address[1..-1])
rescue TypeError
return h[address.first]
end
end
&
不是必需的,因为它接受符号作为第二个参数。您知道如何修改它吗<代码>地址。注入(a,:[])=4将不起作用。。。谢谢@ClothSware-这看起来有点尴尬-类似于:地址[0..-2]。注入(a,:[])[address.last]=4