Unary operators behavior

前端 未结 2 1907
感情败类
感情败类 2021-01-13 08:04

Had some weird results when redefining the unary + operator in Ruby on the Fixnum class. Not exactly sure why things are happening the way they are

2条回答
  •  长发绾君心
    2021-01-13 08:24

    This answer adds additional details to mu's answer.

    Just learned about ruby's Ripper class, and it shows what's happening pretty clearly:

    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]]]]]
    

提交回复
热议问题