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