kin*_*r88 4 ruby arrays indexing multidimensional-array
我有一个数组(外部数组),包含三个数组(内部数组),每个数组有三个元素.
array = [[a, b, c], [d, e, f], [g, h, i]]
Run Code Online (Sandbox Code Playgroud)
我想使用外部数组的索引选择特定的内部数组,然后根据其索引选择所选内部数组中的值.这是我尝试过的:
array.each_index{|i| puts "letter: #{array[i[3]]} " }
Run Code Online (Sandbox Code Playgroud)
我希望能给我以下输出
letter: c letter: f letter: i
Run Code Online (Sandbox Code Playgroud)
但相反,我得到了
letter: [[a, b, c], [d, e, f], [g, h, i]]
Run Code Online (Sandbox Code Playgroud)
我也试过了
array.each_index{|i| puts "letter: #{array[i][3]} " }
Run Code Online (Sandbox Code Playgroud)
但我得到了相同的结果.请任何建议非常感谢.我需要一个简单的解释.
each_index是一个Enumerable,它遍历所有索引并对每个索引执行操作.当它完成后,它将返回您的原始集合,因为它不是它的工作来改变它.如果你想输出的东西在屏幕上通过puts/ print然后each_index是罚款.
如果要通过浏览原始集合的所有元素来创建新集合,则应使用map.
例如
array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
new_array = array.map {|el| el[2]}
=> ["c", "f", "i"]
Run Code Online (Sandbox Code Playgroud)
array.map遍历数组的元素,因此在每个步骤| el |中都是如此 是一个元素,而不是一个索引,如:['a', 'b', 'c']在第一次迭代中,['d', 'e', 'f']在第二次迭代中,依此类推......
只是指出这一点,因为我不知道你想要做的目标是什么.
像这样做:
array.each_index{|i| puts "letter: #{array[i][2]} " }
Run Code Online (Sandbox Code Playgroud)
因为你想要索引2处的字母,而不是3.
数组也应该像这样定义:
array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
Run Code Online (Sandbox Code Playgroud)