verdure
verdure

Reputation: 3341

Ruby String concatenation

I have an array

books = ["Title 1", "Title 2", "Title 3"] 

I need to iterate through this array and get a variable like this:

@books_read = "Title 1 \n Title 2 \n Title 3"

I tried this bit of code:

books.each do |book| 
   @books_read += "#{book} \n"
end

puts @books_read

But, the + operator does not concatenate the strings. Any leads on this please.

Cheers!

Upvotes: 3

Views: 335

Answers (2)

Pedro Nascimento
Pedro Nascimento

Reputation: 13886

You can use join: books.join(" \n ")

Upvotes: 2

Aliaksei Kliuchnikau
Aliaksei Kliuchnikau

Reputation: 13719

You can use Array#join: books.join(" \n ").

join(sep=$,) → str

Returns a string created by converting each element of the array to a string, separated by sep.

Upvotes: 4

Related Questions