CJ Jean
CJ Jean

Reputation: 1131

How can a fixnum be added to a string in ruby?

If I want a string of both words and numbers in ruby, such as "worda, wordb, 12, wordc, 10," do I need to first convert the number to a string ie. a = 12.to_s?

Upvotes: 1

Views: 76

Answers (3)

rposborne
rposborne

Reputation: 802

Ruby requires (approx.) strings to be of the same type, like most reasonable programming languages.

You have 1 solution.

"word" + 12.to_s or "word #{12}"

The second example is called string interpolation, and will call the method .to_s on any object passed in.

Upvotes: 1

Eric Duminil
Eric Duminil

Reputation: 54223

Possible ways to mix strings and integers

It depends how you want to do it :

["worda", 10].join(', ')
"worda, #{10}"
"worda, %d" % 10
"worda" + ", " + 10.to_s
"worda" << ", " << 10.to_s

all return "worda, 10"

join and string interpolation will both call .to_s implicitely.

String + Integer

"worda" + 10

Is a TypeError, though, because there's no implicit conversion with +.

Otherwise "1" + 2 could be either "12" or 3. Javascript accepts it and returns "12", which is a mess IMHO.

String << Integer

Finally:

"worda, " << 10

is a valid Ruby syntax, but it appends the ASCII code 10 (a newline), not the number 10:

"worda, \n"

Upvotes: 6

s1mpl3
s1mpl3

Reputation: 1464

Yes, but you can do

"worda, wordb, #{num_1}, wordc, #{num_2},"

Upvotes: 0

Related Questions