问题描述
在Ruby上的Fixnum
类上重新定义一元+
运算符时,出现了一些奇怪的结果.不确定原因为何发生(特别是009
行).
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 (specifically line 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
推荐答案
我怀疑您在解析器解释数字文字时看到了解析器行为的副作用.
I suspect you're seeing 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
然后看一些事情:
> c = C.new
> +c
=> 11
> ++c
=> 11
这正是我们期望发生的事情.如果我们使用您的Fixnum
一元+
覆盖和Fixnum
变量:
That's exactly what we expect to happen. If we use your Fixnum
unary +
override and a Fixnum
variable:
> n = 23
> +n
=> 15
> ++n
=> 15
然后我们再次看到您的期望.在这两种情况下,我们都看到对非文字对象调用+@
方法的结果.
then again we see what you're expecting. In both cases, we see the result of calling the +@
method on a non-literal.
但是当我们在您的操作员就位的情况下查看+6
时:
But when we look at +6
with your operator in place:
> +6
=> 6
+@
方法未调用.同样,如果我们覆盖-@
:
the +@
method is not called. Similarly if we override -@
:
class Fixnum
def -@
'pancakes'
end
end
并查看其作用:
> -42
=> 42
那么这是怎么回事?好吧,Ruby看到+6
和-42
并不是作为6.send(:+@)
和42.send(:-@)
方法调用,而是作为正6和负42的单个文字.
So what's going on here? Well, Ruby is seeing +6
and -42
not as 6.send(:+@)
and 42.send(:-@)
method calls but as single literals for positive six and negative forty-two.
如果您开始添加括号+(6)
和-(42)
,则Ruby会看到非文字表达式并最终调用一元方法.同样,当您将一元运算符加倍时.
If you start adding parentheses, +(6)
and -(42)
, then Ruby sees non-literal expressions and ends up calling the unary methods. Similarly when you double the unary operators.
这篇关于一元运算符的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!