Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/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
循环遍历数组ruby_Ruby_Loops - Fatal编程技术网

循环遍历数组ruby

循环遍历数组ruby,ruby,loops,Ruby,Loops,我有一组数字123456789 我正在写一个循环,所以每3个数字/字符就插入一个逗号,然后开始一个新行 我将使用哪种类型的环路?我如何告诉ruby每3个数字“123456.每个字符限制(3)”?我知道limit不正确,但希望我能理解这个想法。如果这组数字是一个字符串,您可以使用它将字符分成3组,然后在打印到控制台之前将它们连接在一起: [21] pry(main)> "123456789".chars.each_slice(3) { |a| p "#{a.join}," } "123,"

我有一组数字
123456789

我正在写一个循环,所以每3个数字/字符就插入一个逗号,然后开始一个新行


我将使用哪种类型的环路?我如何告诉ruby每3个数字<代码>“123456.每个字符限制(3)”?我知道limit不正确,但希望我能理解这个想法。

如果这组数字是一个字符串,您可以使用它将字符分成3组,然后在打印到控制台之前将它们连接在一起:

[21] pry(main)> "123456789".chars.each_slice(3) { |a| p "#{a.join}," }
"123,"
"456,"
"789,"
结果:

123,
456,
789,
备选环路:

"123456789".each_char.with_index(1) do |item, index|
    if index % 3 == 0
        print item + ",\n"
    else
        print item
    end          
end

这组数字是数组还是字符串?
"123456789".each_char.with_index(1) do |item, index|
    if index % 3 == 0
        print item + ",\n"
    else
        print item
    end          
end