我有一个字符串:results = "123 456 "
我想遍历字符串并打印:“1,2,3 ,, 4,5,6,”
到目前为止,这是我的代码:
results.each do |k|
print k, ","
end
我也尝试过使用each_char
。
答案 0 :(得分:1)
这应该有效:
results.split('').join(',')
# => "1,2,3, ,4,5,6, "
答案 1 :(得分:1)
results.each_char.map
# => ["1", "2", "3", " ", "4", "5", "6", " "]
或者,如果您想要一个字符串作为输出:
result.each_char.map.join(',')
# => "1,2,3, ,4,5,6, "
答案 2 :(得分:1)
each_char
适合我:
results = "123 456 "
results.each_char do |char|
print "#{char},"
end
输出:
1,2,3, ,4,5,6, ,
答案 3 :(得分:1)
"123 456 ".gsub(/(?<!\A)(?!\z)/, ",")
# => "1,2,3, ,4,5,6, "