gpt4 book ai didi

ruby - 循环遍历数组 ruby

转载 作者:太空宇宙 更新时间:2023-11-03 18:14:26 25 4
gpt4 key购买 nike

我有一组数字123456789

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

我会为此使用什么类型的循环?我如何告诉 ruby 每 3 个数字? “123456.each_char.limit(3)”?我知道限制是不正确的,但希望我能理解这个想法。

最佳答案

puts 123456789.to_s.gsub(/(.{3})/,"\\1,\n")

结果:

123,
456,
789,

替代循环方式:

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

关于ruby - 循环遍历数组 ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28490311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com