Reputation: 3
New user here, so I apologise if this post wasn't formatted correctly.
I am learning how to write Ruby, and I'm using Notepad++. One of the files I'm working on is todemu.rb, which is a file that tells you details about a character called Todemu.
One of the methods I added was:
todemu.age = "27"
to show the age. Then, I put that into a variable so it'd be easier for me to insert that in a sentence.
x = todemu.age
puts "How old is Todemu?"
puts "Todemu is" + " " + x.to_s + " " + "years old."
which displays the output I wanted, Todemu is 27 years old.
Then, I tried to increase the value of the age by using this bit of code:
x += 1
Yet, the console in Notepad++ (I used the NppExec plugin for this) showed this error:
todemudan.rb:26:in '+': No implicit conversion of Integer into String (TypeError)
Why does it show the plus sign in the error, and how do I fix this?
Also, I have looked into most of the similarly worded questions in Stack Overflow, but none seem to rectify my problem (thanks iGian for reminding me).
Thanks in advance, and I apologise for the length of the post.
Upvotes: 0
Views: 2673
Reputation: 834
You can call .to_i
method on the string which represents number. .to_i
will coerce the string to integer and .to_f
will convert it as float. But make sure string represents number. If you call 'number'.to_i
it will return zero
Upvotes: 0
Reputation: 2532
You keep the age in a String and are trying to apply the “+” operator with an Integer. You should probably store the age as an Integer so you can add to it using “+”. If that is not possible you can always cast using .to_i before adding, eg:
age = x.to_i+1
I’d suggest going through some tutorials that cover Ruby’s type system, for instance: http://zetcode.com/lang/rubytutorial/datatypes/
Ruby's type system forces you to mind your types in such cases rather than for instance PHP's + operator which will concatenate if one of the parameters is a string and the other an integer (without throwing an error)
Integer adding
i = 1
i + 1 # => 2
String + Integer
i = "1"
i + 1 # => error
i.to_i + 1 # => 2
i + "1" # => 11
Interpolation
i = 27
puts "My age is #{i}" # => My age is 27
Upvotes: 4