0

I have an array set up like

%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

This will output something similar like

Dog + 0
Cat + 1
Bird + 2
Rat + 3

What if I want to change the animals to something such as a string? So that it says

This is string 0 + 0
This is string 1 + 1
This is string 2 + 2
etc

Is there a way to do that? This does not work:

%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
1
  • 4.times { |i| puts "This is string #{i} + #{i}" } Commented Aug 6, 2017 at 18:36

2 Answers 2

4

If you want that your arrays can contain strings with spaces build it in the regular way.

['This is string 0', 'This is string 1', 'This is string 2', 'This is string 3'].each_with_index do |element, index|

Note that this could be written in many ways. One shorter way is

(0..3).map { |i| "This is string #{i}" }.each_with_index do |element, index|
Sign up to request clarification or add additional context in comments.

Comments

3

Just use the "normal" array syntax:

['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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.