1

How can I iterate through an array of numbers, and add a string to the output in each iteration? I'm using "puts" to display the number.

The array

nums = Array[1, 2, 3, 4, 5]

Iterating the array

for i in nums
    puts i + " Carrots"
end

I'm getting this response

test.rb:40:in `+': String can't be coerced into Integer (TypeError)String can't be coerced into Integer (TypeError)String can't be coerced into Integer (TypeError)
1
  • 1
    Convert the integer into string: i.to_s Commented Dec 25, 2018 at 15:37

3 Answers 3

1

Method 1: Using to_s

You can use to_s to convert integer to string.

nums = Array[1, 2, 3, 4, 5]

for i in nums
    puts i.to_s + " Carrots"
end

output:

1 Carrots
2 Carrots
3 Carrots
4 Carrots
5 Carrots

Method 2: Using String Interpolations

nums = Array[1, 2, 3, 4, 5]

for i in nums
    puts "#{i}  Carrots"
end

Output:

1  Carrots
2  Carrots
3  Carrots
4  Carrots
5  Carrots

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

1

Just out of curiosity:

puts [1, 2, 3, 4, 5].product([" Carrots"]).map(&:join)
#⇒ 1 Carrots
#  2 Carrots
#  3 Carrots
#  4 Carrots
#  5 Carrots

Comments

0

You can convert the number using the method to_s and concatenate with +, or use interpolation, but looping with for doesn't feels like the ruby way

Using iterators

nums = [1, 2, 3, 4]

nums.each do |num|
  puts num.to_s + ' Carrots'
end

nums.each do |num|
  puts "#{num} Carrots"
end

Note: Use simple quotes if interpolation is not going to be used

More elegant one line solution

puts nums.map {|num| num.to_s + ' Carrots'}

puts nums.map {|num| "#{num} Carrots"}

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.