如何正确地将数组元素分成字符串?

时间:2017-08-06 17:41:05

标签: arrays ruby

我有一个像

这样的数组
%w(Dog Cat Bird Rat).each_with_index do |element, index|
# "w" for word array
# It's a shortcut for arrays

  puts ("%-4s + #{index}" % element)    
end

这将输出类似

的内容
Dog + 0
Cat + 1
Bird + 2
Rat + 3

如果我想将动物变成诸如弦之类的东西怎么办? 所以说它

This is string 0 + 0
This is string 1 + 1
This is string 2 + 2
etc

有办法吗? 这不起作用:

%w('This is string 0', 'This is string 1', 'This is string 2', 'This is string 3').each_with_index do |element, index|
# "w" for word array
# It's a shortcut for arrays

  puts ("%-4s + #{index}" % element)    
end

2 个答案:

答案 0 :(得分:4)

如果您希望您的数组可以包含带空格的字符串,请以常规方式构建它。

['This is string 0', 'This is string 1', 'This is string 2', 'This is string 3'].each_with_index do |element, index|

请注意,这可以通过多种方式编写。一个较短的方法是

(0..3).map { |i| "This is string #{i}" }.each_with_index do |element, index|

答案 1 :(得分:3)

只需使用“普通”数组语法:

['This is string 0', 'This is string 1', 'This is string 2', 'This is string 3'].each_with_index do |element, index|
  puts ("%-4s + #{index}" % element)    
end

This is string 0 + 0
This is string 1 + 1
This is string 2 + 2
This is string 3 + 3