키 이름으로 루비에서 다차원 해시에서 특정 값 추출
-
19-09-2019 - |
문제
다차원 해시가 있고, 서브 해시 중 하나에는 키에 의해 검색되어야하는 key => value 쌍이 있습니다. 어떻게하니?
예제 해시 :
h={:x=>1,:y=>2,:z=>{:a=>{:k=>"needle"}}}
h={:k=>"needle"}
열쇠는 항상 : k, "바늘"을 가져와야합니다.
루비 1.8에는 해시에 "평평한"기능이 없다는 것을 알았지 만, 그것이 있다면, 나는 그냥 할 것입니다.
h.flatten[:k]
재귀 기능을 작성해야한다고 생각합니까?
감사해요
해결책
당신은 항상 당신을 위해 더러운 일을하는 해시에 자신의 미션-특정 확장을 쓸 수 있습니다.
class Hash
def recursive_find_by_key(key)
# Create a stack of hashes to search through for the needle which
# is initially this hash
stack = [ self ]
# So long as there are more haystacks to search...
while (to_search = stack.pop)
# ...keep searching for this particular key...
to_search.each do |k, v|
# ...and return the corresponding value if it is found.
return v if (k == key)
# If this value can be recursively searched...
if (v.respond_to?(:recursive_find_by_key))
# ...push that on to the list of places to search.
stack << v
end
end
end
end
end
당신은 이것을 아주 간단하게 사용할 수 있습니다 :
h={:x=>1,:y=>2,:z=>{:a=>{:k=>"needle"}}}
puts h.recursive_find_by_key(:k).inspect
# => "needle"
h={:k=>"needle"}
puts h.recursive_find_by_key(:k).inspect
# => "needle"
puts h.recursive_find_by_key(:foo).inspect
# => nil
다른 팁
단순히 키 값을 가져와야하지만 키가 얼마나 깊는 지 모른다면이 스 니펫을 사용하십시오.
def find_tag_val(hash, tag)
hash.map do |k, v|
return v if k.to_sym == tag
vr = find_tag_val(v, tag) if v.kind_of?(Hash)
return vr if vr
end
nil #othervice
end
h = {message: { key: 'val'}}
find_tag_val(h, :key) #=> 'val'
제휴하지 않습니다 StackOverflow