Reputation: 1131
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
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
Reputation: 54223
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.
"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.
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