2017-08-06 11 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倍を{| I | puts "これは文字列#{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| 
関連する問題