Arrays 如何正确地将数组元素分隔成字符串?
我有一个像这样的数组Arrays 如何正确地将数组元素分隔成字符串?,arrays,ruby,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
%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
如果希望数组可以包含带空格的字符串,请按常规方式构建
['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|
只需使用普通数组语法:
['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
4.times{i}放置这是字符串{i}+{i}