关于 Ruby Gsub
params[:hello] # => "Some params value"
hello = params[:hello]
hello.gsub!("whatever","")
params[:hello] # => ""
我不明白,有人可以解释一下为什么 params[:hello]
被 gsub!
修改吗?我预计 hello
字符串会被修改,但 params
哈希值不会被修改。
params[:hello] # => "Some params value"
hello = params[:hello]
hello.gsub!("whatever","")
params[:hello] # => ""
I don't understand, can someone please explain why the params[:hello]
gets modified by the gsub!
? I expected the hello
string to be modified, but not the params
hash.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
hello
和params[:hello]
是对同一字符串的引用。在 ruby 中(如在 java 和 python 中),赋值不会复制值,它只是在被赋值变量中存储对相同值的另一个引用。因此,除非您在修改字符串之前显式复制该字符串(使用 dup),否则对该字符串的任何更改都将影响对该字符串的所有其他引用。hello
andparams[:hello]
are references to the same string. In ruby (as in java and python among others) assignment does not copy the value, it just stores another reference to the same value in the assigned-to variable. So unless you explicitly copy the string before modifying it (usingdup
) any changes to the string will affect all other references to the string.String#gsub
有两个版本可用String#gsub!
修改原始字符串并返回对其的引用。String#gsub
不会修改原始内容并在副本上进行替换。用
!
来命名修改对象的方法是一种常见的 Ruby 习惯用法。There are two versions of
String#gsub
availableString#gsub!
modifies the original string and returns a reference to it.String#gsub
does not modify the original and makes the replacement on a copy.It is a common ruby idiom to name methods which modify the object with a
!
.如果您不想修改它,则需要克隆它,例如:
按照您现在的方式,您拥有对它的引用,而不是副本。
If you don't want it to be modified, you need to clone it, like:
The way you're doing it now, you have a reference to it, not a copy.