Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何使用值数组作为数组/哈希路径?_Arrays_Ruby - Fatal编程技术网

Arrays 如何使用值数组作为数组/哈希路径?

Arrays 如何使用值数组作为数组/哈希路径?,arrays,ruby,Arrays,Ruby,也就是说,我是如何从中获得的: path = [ 1, 3, 4, 5 ... ] 为此: my_array[1][3][4][5]... 路径数组的长度未知。肯定不是要走的路,只是为了好玩: def build_path(array, path) eval "#{array}#{path.map { |el| "[#{el}]" }.join}" end build_path([1,2], [1]) #=> 2 您可以使用新的(Ruby 2.3)dig方法,如下所示: my_a

也就是说,我是如何从中获得的:

path = [ 1, 3, 4, 5 ... ]
为此:

my_array[1][3][4][5]...

路径数组的长度未知。

肯定不是要走的路,只是为了好玩:

def build_path(array, path)
  eval "#{array}#{path.map { |el| "[#{el}]" }.join}"
end
build_path([1,2], [1])
#=> 2
您可以使用新的(Ruby 2.3)
dig
方法,如下所示:

my_array.dig(1, 3, 4, 5)
或者将其传递给飞溅的阵列:

path = [1, 3, 4, 5]
my_array.dig(*path)

您还可以将
inject
[]
结合使用:

irb(main):001:0> arr = [[[[0, 1]]]]
=> [[[[0, 1]]]]
irb(main):002:0> [0, 0, 0, 1].inject(arr, :[])
=> 1
这将使用
[]
递归地“解包”arr,直到
inject
耗尽路径元素


这不需要特定的版本(
inject
至少从Ruby 1.8开始就是Enumerable的一部分),但可能需要一条注释来解释发生了什么。

你指的是自动激活吗?看

你可以这样做

def hash_tree
  Hash.new do |hash, key|
    hash[key] = hash_tree
  end
end

myhash = hash_tree 
myhash[1][2][3][4] = 5
myhash # {1=>{2=>{3=>{4=>5}}}}
myhash[1][2][3][4] # 5
或者如果你喜欢博客上的例子

def autovivifying_hash
  Hash.new {|ht,k| ht[k] = autovivifying_hash}
end

棒极了,完美的解决方案+1