简体   繁体   English

如果我有一个数组数组,如何分隔数组?

[英]If I have an array of arrays, how do I separate the arrays?

I have an array that consists of other arrays, for example [[1, 52], [30, 1], [2, 1]] . 我有一个包含其他数组的数组,例如[[1, 52], [30, 1], [2, 1]] I would like to use each individual array separately. 我想分别使用每个单独的数组。 Using a loop just breaks it down to all the numbers individually. 使用循环只会将其分解为所有数字。

arrays = [[1, 52], [30, 1], [2, 1]]

irb(main):003:0* arrays.each do |array|
irb(main):004:1* puts array
irb(main):005:1> end
1
52
30
1
2
1
=> [[1, 52], [30, 1], [2, 1]]

I'd like to loop through the arrays. 我想遍历数组。 What function can I use for this? 我可以使用什么功能?

I'd like puts array to display this instead; 我想把puts array显示出来;

[1, 52]
[30, 1]
[2, 1]

You are looping through the arrays. 正在遍历数组。 The puts function on its own just makes that difficult to see. puts函数本身很难看清。 Try this: 尝试这个:

arrays = [[1, 52], [30, 1], [2, 1]]

arrays.each do |array|
  puts array.inspect
end

Output: 输出:

[1, 52]
[30, 1]
[2, 1]

See also: 也可以看看:

puts [1, 2, 3]

Output: 输出:

1
2
3
p array

................................. .................................

You are looping through the arrays, it's just that puts() doesn't output an array so that it looks like an array. 正在遍历数组,只是puts()不输出数组,因此看起来像数组。 When you give puts() an array as an argument, it outputs each element separated by newlines. 当给puts()一个数组作为参数时,它将输出用换行符分隔的每个元素。

Examine the output here: 在这里检查输出:

arrays = [[1, 52], [30, 1], [2, 1]]

arrays.each do |x|
  puts x.class
  puts x.size
  puts x[-1]
end

--output:--
Array
2
52
Array
2
1
Array
2
1

The output shows that each() assigns each inner array to the loop variable x . 输出显示each()将每个内部数组分配给循环变量x Likewise, Array methods, like size() and [] work on x . 同样,像size()[]这样的Array方法也可以在x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM