Ruby中的一元加运算符有什么意义? [英] What's the point of unary plus operator in Ruby?

查看:87
本文介绍了Ruby中的一元加运算符有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了与一元减号很好地对称之外,为什么在Numeric类上定义一元加号运算符?除了引起混乱之外,它允许编写++i之类的东西(与大多数非Ruby主义者不同,它不会增加i),因此它具有一些实用价值.

Apart from making a nice symmetry with unary minus, why is unary plus operator defined on Numeric class? Is there some practical value in it, except for causing confusion allowing writing things like ++i (which, unlike most non-Rubyists would think, doesn't increment i).

我可以想到这样的情况:在自定义类上定义一元加号可能会很有用(例如,如果您正在创建一些性感的DSL),因此能够对其进行定义是可以的,但是为什么它已经在Ruby数字上进行了定义?

I can think of scenario where defining unary plus on a custom class could be useful (say if you're creating some sexy DSL), so being able to define it is ok, but why is it already defined on Ruby numbers?

推荐答案

也许与其他编程语言的一致性以及镜像一元减号的一致性只是一个问题.

Perhaps it's just a matter of consistency, both with other programming languages, and to mirror the unary minus.

Found support for this in The Ruby Programming Language (written by Yukihiro Matsumoto, who designed Ruby):

一元加号是允许的,但是它对数字操作数没有影响—它只是返回其操作数的值.它是为一元负的对称性提供的,当然可以重新定义.

The unary plus is allowed, but it has no effect on numeric operands—it simply returns the value of its operand. It is provided for symmetry with unary minus, and can, of course, be redefined.

这篇关于Ruby中的一元加运算符有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆