Undefined `- 'method for" 100 ": String

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 automatically convert strings to numbers when performing mathematical operations on them?

+5
source share
2 answers

Ruby is a dynamically typed , strictly-typed (or "strongly typed") language, Lua is another such language. The first means that variables can contain any class of values. The latter - what you use means that type enforcement does not happen automatically.

JavaScript, . JavaScript var x = [] + false;, - . , JavaScript "1" + 1 == "11", "1" - 1 == 0. Ruby .

:

puts income.to_i - bills.to_i

, , Ruby, , . :

class Person
  def +( something )
    if something.is_a?(Numeric)
      self.weight += something
    elsif something.is_a?(Time)
      self.age += something
    else
      raise "I don't know how to add a #{something.class} to a Person."
    end
  end
end

.

+13

+, , , .

, , (int float), - :

income = "100"
bills  = "52"

puts income.to_f - bills.to_f
+6

All Articles