desbest
desbest

Reputation: 4896

How do I append a variable to another variable in Ruby?

I can't find the answer using Google.

Works!

i = 15
appended = "Dark " << "Silk"
appended = appended

Doesn't work. :(

i = 15
appended = "Dark " << i
appended = appended

Upvotes: 0

Views: 1431

Answers (3)

Andr&#233; Medeiros
Andr&#233; Medeiros

Reputation: 810

"Silk" is a string and 15 is an integer. You can ONLY concatenate and string to another string. That's why "Dark" << "Silk" works. If you first transform 15 into a string with 15.to_s, you'll be able to concatenate it.

I suggest you read through Ruby's documentation to find out more about built-in classes and methods.

Upvotes: 2

robbrit
robbrit

Reputation: 17960

Try this:

i = 15
appended = "Dark " + "Silk"

or for non-String objects:

appended = "Dark " + i.to_s

You can also use string interpolation (which is more idiomatic):

appended = "Dark #{i}"

Upvotes: 9

Renra
Renra

Reputation: 5649

Does

"Dark" << i.to_s

do what you want?

Upvotes: 2

Related Questions