Unary Operator Behavior

There were some strange results when overriding a unary operator +in Ruby in a class Fixnum. It is not entirely clear why everything happens as they are (in particular, a string 009).

irb:003> class Fixnum
irb:004>   def +@ #define unary +
irb:005>     15
irb:006>   end
irb:007> end
=> nil
irb:008> 2
=> 2
irb:009> +2
=> 2
irb:010> +(2)
=> 15
irb:011> ++2
=> 15
+4
source share
2 answers

I suspect that you see a side effect of the parser's behavior in how it interprets numeric literals.

If we create our own class:

class C
  def +@
    11
  end
end

and then look at some things:

> c = C.new
> +c
 => 11 
> ++c
 => 11 

That is what we expect. If we use the override of Fixnumunary +and a Fixnum:

> n = 23
> +n
 => 15 
> ++n
 => 15 

, . +@ .

+6 :

> +6
 => 6 

+@ . , -@:

class Fixnum
  def -@
    'pancakes'
  end
end

, :

> -42
 => 42

, ? , Ruby +6 -42 6.send(:+@) 42.send(:-@), .

, +(6) -(42), Ruby . , .

+4

mu.

Ripper, , :

require 'ripper'

p Ripper.sexp('2')     # => [:program, [[:@int, "2", [1, 0]]]]
p Ripper.sexp('+2')    # => [:program, [[:@int, "+2", [1, 0]]]]
p Ripper.sexp('+(2)')  # => [:program, [[:unary, :+@, [:paren, [[:@int, "2", [1, 2]]]]]]]
p Ripper.sexp('++2')   # => [:program, [[:unary, :+@, [:@int, "+2", [1, 1]]]]]
+1

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


All Articles