为什么没有赋值运算符就可以在没有编译器警告的情况下修改Ruby常量? [英] Why does the absence of the assignment operator permit me to modify a Ruby constant with no compiler warning?

查看:75
本文介绍了为什么没有赋值运算符就可以在没有编译器警告的情况下修改Ruby常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的两个示例中,我做同样的事情,创建一个常量String并使用concat方法对其进行修改。因为它是一个常数,所以我希望得到编译器警告,但是当我使用赋值运算符时,在第二个示例中只会收到一个警告。为什么会这样?

In the following two examples I do the same thing, creating a constant String and using the concat method to modify it. Because it's a constant, I expect a compiler warning but only receive one in the second example when I use the assignment operator. Why is this?

X = "hello"
X.concat(" world")
puts X # no warning

X = "hello"
X = X.concat(" world")
puts X # warning: already initialized

由于concat方法会在适当的位置修改字符串,因此通常这样做是因为不需要使用分配运算符。那么,为什么赋值运算符的存在会导致编译器将这两个操作标识为不同?

Since the concat method modifies the string in place, that's normally what I would do, since there's no need to use an assigment operator. So, why does the presence of the assignment operator cause the compiler to identify these two operations as being different?

推荐答案

这是因为您正在重新定义一个新的X。重新定义常量时,它会给您已初始化错误。第一个示例未给出此错误,因为您没有重新定义X,而是对其进行了修改。

This is because you're re-defining a new X. When you redefine a constant it gives you the "already initialized" error. The first example does not give this error because you're not redefining X, you're modifying it.

这篇关于为什么没有赋值运算符就可以在没有编译器警告的情况下修改Ruby常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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