[英]Ruby hash access value from string array
我有一个像下面这样的哈希:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.