This Ruby code:
income = "100"
bills = "52"
puts income - bills
threw an error:
./to_f.rb:6: undefined method `-' for "100":String (NoMethodError)
Does Ruby not auto-convert strings to numbers when performing math operations on them?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Ruby is a dynamically-typed, strictly-typed (or “strongly-typed”) language. Lua is another such language. The former means that variables can hold any class of value. The latter—what you are running into—means that type coercion does not happen automatically.
Contrast these with JavaScript, which is dynamically-typed and loosely-typed. In JavaScript you can write
var x = [] + false;and it will attempt to do something helpful. For another example, in JavaScript"1" + 1 == "11"but"1" - 1 == 0. Ruby will not do any such thing.In your case you need:
Note that—because most operators are implemented as methods in Ruby—each class can choose how the operator handles operands of various types. For example:
Most of the time the core libraries do not attempt to be so clever, however.