-1

我有一个字符串:results = "123 456 "

我想遍历字符串并打印:“1,2,3, ,4,5,6,”

到目前为止,这是我的代码:

results.each do |k|
  print k, ","
end

我也尝试过使用each_char.

4

4 回答 4

1

这应该有效:

results.split('').join(',')
# => "1,2,3, ,4,5,6, "
于 2013-10-25T14:28:18.967 回答
1
results.each_char.map
# => ["1", "2", "3", " ", "4", "5", "6", " "]

或者,如果您想要一个字符串作为输出:

result.each_char.map.join(',')
# => "1,2,3, ,4,5,6, "
于 2013-10-25T14:31:54.630 回答
1

each_char为我工作:

results = "123 456 "
results.each_char do |char|
  print "#{char},"
end

输出:

1,2,3, ,4,5,6, ,
于 2013-10-25T14:38:22.283 回答
1
"123 456 ".gsub(/(?<!\A)(?!\z)/, ",")
# => "1,2,3, ,4,5,6, "
于 2013-10-25T15:27:38.347 回答