我有这样的Hash,表示一个数据树
hash = {
'key1' => {
'sub1' => 1,
'sub2' => 2
},
'key2' => 3
}我想用一个表示路径的键数组来探索树。下面是一些例子:
使用一个简单的路径:
keys = ['key2']我想让3
使用以下路径:
keys = ['key1', 'sub1']我想让1
使用无效路径:
keys = ['key1', 'sub1', 'blabla']
keys = ['key1', 'blabla']获取nil
等等。等等。你明白我的意思了
发布于 2012-03-04 08:51:35
keys.inject(hash) {|acc, value| acc[value]}发布于 2012-03-04 08:52:25
不执行任何错误检查,但是
h = {'k1' => {'s1' => 1, 's2' => 2}, 'k2' => 3}
ks = ['k1', 's1']
ks.inject(h){|hh, k| hh[k]} # => 1
['k1', 's2'].inject(h){|hh, k| hh[k]} # => 2
['k2'].inject(h){|hh, k| hh[k]} # => 3发布于 2012-03-04 09:13:43
最好将对象放在心上,让我们向Hash类添加一个功能
# in intialize or whatever
class Hash
def find_path path #recursive
key = path.first
if _path.size == 1 # end of path => return value
[key]
elsif [key].kind_of?(Hash) # continue
[key].find_path path[1..-1]
else # have to continue but not a has => out
nil
end
end
def find_path path # not recursive
_path = path.clone #copy to shift
_tree = self #start with self
while(_path.size > 1 && _tree) do #while not the end and _tree
_v = _tree[_path.shift]
_tree = _v.kind_of?(Hash) ? _v : nil
end
_tree ? _tree[_path.first] : nil
end
end这样:
hash = {:v1 => {:v1.1 => "yes", :v1.2 => "false"}}
hash.find_path [:v1, :v1.1]
# => "yes"
hash.find_path [:v1]
# => {:v1.1 => "yes", :v1.2 => "false"}
hash.find_path [:v2]
# => nil
hash.find_path [:v1, :v1.3]
# => nilhttps://stackoverflow.com/questions/9551257
复制相似问题