Concatenate a string and an integer?
-
Does Ruby have this ability? It appear to me it does not, unless my search and coding is in error.
For example:
opposite=4; adjacent=3; angle=Math.atan(4/3).radians
45.0
string=".degrees"
.degrees
angle1=angle+string
Error: #<TypeError: (eval):4542:in `+': String can't be coerced into Float>
(eval):4542
(eval):4542FYI: Autolisp: can concatenate a string and an integer: such that
angle1=angle+string
45.degrees -
In ruby objects have a certain type and you can rely on that the type does not magically change on its own.
For a number, the+
method is defined to accept another number as argument and returns a number (that you don't want).
For a string, the+
concatenates strings and returns the resulting string, so you have to convert any object into a string first.There are many ways to create strings:
string concatenation:
90.to_s + " degrees"
# slow because it creates a new third string object
string appending:
90.to_s << " degrees"
# faster because it adds the second string into the first
string interpolation:
"#{90} degrees"
-
thanks for the explanation Aerilius:
opposite=4; adjacent=3; angle=Math.atan(4/3).radians
45.0
string=".degrees"
.degrees
angle1=angle.to_s << ".degrees"
45.0.degreesIts also great news because it finally allows me to make the acceptable 45.0.degrees substitution into the Sine Law that TIG was so kind to put into Ruby form.
http://sketchucation.com/forums/viewtopic.php?f=180&t=53118 -
@aerilius said:
There are many ways to create strings:
string concatenation:
90.to_s + " degrees"
# slow because it creates a new third string object
string appending:
90.to_s << " degrees"
# faster because it adds the second string into the first
string interpolation:
"#{90} degrees"
Note that string interpolation is the fastest. (And reads easier IMO)
Advertisement