2017-08-06 53 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| 
相關問題