Why does adding string + fixnum generate a coercion error?

Why can't adding ruby ​​force this string to fixnum and vice verca?

irb>fixnum = 1
=> 1
irb> fixnum.class
=> Fixnum
irb> string = "3"
=> "3"
irb> string.class
=> String
irb> string.to_i
=> 3
irb> fixnum + string
TypeError: String can't be coerced into Fixnum
    from (irb):96:in `+'
    from (irb):96
    from :0
irb(main):097:0> 
+3
source share
4 answers

Since ruby ​​does not know if you want to convert the string to int or int to string. In particular. java 1 + "3"- "13". Ruby prefers to raise an error so that the user can decide whether to_sone operand or the to_iother should do the wrong thing automatically.

+10
source

, , . + fixnum . , int int . :

str = "5"
num =  3

puts str.to_i + num
=> 8

puts str + num.to_s
=> 53

, , , Ruby .

+5

, .to_i , .

>> string = "3"
=> "3"
>> string.class
=> String
>> string.to_i
=> 3
>> string
=> "3"
>> string.class
=> String
>> string = string.to_i
=> 3
>> string.class
=> Fixnum
+1

Fixnum#+ - . :

class Fixnum
  def +(other)
    if Fixnum === other
      # normal operation
    else
      n1, n2= other.coerce(self)
      return n1+n2
    end
  end
end

coerce . , , 42 + 3.141. . String, .

class String
  def coerce(other)
    coerced= case other
    when Integer
      self.to_i
    when
      self.to_f
    end
    return coerced, other
  end
end

23 + "42" # => 65
0.859 - "4" # => 3.141

. coerce "23" + 42 . String#+ .

+ Fixnum, Integer. Fixnum Bignum , .

+1

Source: https://habr.com/ru/post/1719863/


All Articles