2017-08-06 109 views
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 
+0

'4.times {|我|放入“这是字符串#{i} +#{i}”}' –

回答

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 
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| 
相关问题