Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何正确地将数组元素分隔成字符串?_Arrays_Ruby - Fatal编程技术网

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}