我正在尝试编写一个循环,该循环接受一个嵌套数组并一次生成一个包含两个连续元组的子数组。输入数组可能是这样的
arr = [['A','B'],['C','D'],['E','F'],['G','H'],['I','J'],['K','L'],
['M','N'],['O','P']]
Output: ['A','B'],['C','D']
['E','F'],['G','H']
['I','J'],['K','L']
['M','N'],['O','P']
我尝试了各种循环,比如
arr.each_slice(2) do |k,m|
new_arr=[k,m]
puts new_arr
end
和
arr.each_slice(2) { |k,m| puts(k,m) }
这有什么问题吗?在这两种情况下,输出都是
A
B
C
D .....
最佳答案
这就是 puts
在 ruby 1.9 中处理数组的方式,it prints each element on a new line .结果就是您想要的,只是打印时看起来不同 :) 例如,尝试使用 .inspect
进行打印。
arr = [['A','B'],['C','D'],['E','F'],['G','H'],['I','J'],['K','L'],
['M','N'],['O','P']]
arr.each_slice(2) do |k,m|
new_arr = [k,m]
puts new_arr.inspect
end
# >> [["A", "B"], ["C", "D"]]
# >> [["E", "F"], ["G", "H"]]
# >> [["I", "J"], ["K", "L"]]
# >> [["M", "N"], ["O", "P"]]
http://www.ruby-doc.org/core-1.9.3/IO.html#method-i-puts
puts(obj, ...) → nil
Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.
$stdout.puts("this", "is", "a", "test")
产生:
this
is
a
test
关于ruby - 从更大的数组创建子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12997903/