Ruby 中没有增量运算符 (++)? [英] No increment operator (++) in Ruby?

查看:32
本文介绍了Ruby 中没有增量运算符 (++)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
为什么 Ruby 不支持 i++ 或 i—为fixnum?

为什么 Ruby 中没有增量运算符?

例如

i++++我

++ 运算符是否用于其他用途?这有真正的原因吗?

解决方案

Ruby 没有前/后自增/自减运算符.例如,x++x-- 将无法解析.更重要的是,++x--x 什么都不做!事实上,它们表现为多个一元前缀运算符: -x == ---x == -----x == ...... 要增加一个数字,只需编写 <代码>x += 1.

摘自《Ruby 新手应该知道的事情》" (存档镜像)

这比我以往任何时候都更能解释它.

以及语言作者本人的原因(来源):

<块引用>

  1. ++ 和 -- 不是 Ruby 中的保留运算符.
  2. C 的递增/递减运算符实际上是隐藏赋值.它们影响变量,而不是对象.您无法通过方法完成分配.Ruby 改用 +=/-= 运算符.
  3. self 不能成为赋值的目标.此外,更改整数 1 的值可能会导致整个程序的严重混乱.

Possible Duplicate:
Why doesn't Ruby support i++ or i— for fixnum?

Why is there no increment operator in Ruby?

e.g.

i++
++i

Is the ++ operator used for something else? Is there a real reason for this?

解决方案

Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ...... To increment a number, simply write x += 1.

Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)

That explains it better than I ever could.

EDIT: and the reason from the language author himself (source):

  1. ++ and -- are NOT reserved operator in Ruby.
  2. C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
  3. self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.

这篇关于Ruby 中没有增量运算符 (++)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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