我有一个如下的哈希:
hash = {"a": [{"c": "d", "e": "f"}] }
通常我们可以像访问它一样访问它hash["a"][0]["c"]
。
但是,我有一个像这样的字符串:
string = "a[0]['c']"
(这可以根据用户输入而改变)
有没有使用上述字符串值访问哈希的简单方法?
我有一个如下的哈希:
hash = {"a": [{"c": "d", "e": "f"}] }
通常我们可以像访问它一样访问它hash["a"][0]["c"]
。
但是,我有一个像这样的字符串:
string = "a[0]['c']"
(这可以根据用户输入而改变)
有没有使用上述字符串值访问哈希的简单方法?
假设用户输入数组索引的数字和哈希键的单词:
keys = string.scan(/(\d+)|(\w+)/).map do |number, string|
number&.to_i || string.to_sym
end
hash.dig(*keys) # => "d"
你可以这样做:
hash = { 'a' => [{ 'c' => 'd', 'e' => 'f' }] }
string = "a[0]['c']"
def nested_access(object, string)
string.scan(/\w+/).inject(object) do |hash_or_array, i|
case hash_or_array
when Array then hash_or_array[i.to_i]
when Hash then hash_or_array[i] || hash_or_array[i.to_sym]
end
end
end
puts nested_access(hash, string) # => "d"
扫描输入字符串中的字母、下划线和数字。其他一切都被忽略:
puts nested_access(hash, "a/0/c") #=> "d"
puts nested_access(hash, "a 0 c") #=> "d"
puts nested_access(hash, "a;0;c") #=> "d"
不正确的访问值将返回 nil。
它也适用于符号作为键:
hash = {a: [{c: "d", e: "f"}]}
puts nested_access(hash, "['a'][0]['c']")
它带来了对用户输入不太严格的优点,但它确实具有无法识别带有空格的键的缺点。
您可以使用gsub
将其他字符清理到数组中并使用该数组来访问您的哈希
hash = {"a": [{"c": "d", "e": "f"}] }
string = "a[0]['c']"
tmp = string.gsub(/[\[\]\']/, '').split('')
#=> ["a", "0", "c"]
hash[tmp[0].to_sym][tmp[1].to_i][tmp[2].to_sym]
#=> "d"