需要帮助理解一些 Ruby 代码
前几天我正在查看字符串转义库中的一些代码,我遇到了一些如下所示的代码:
class StringWrapper
class << self
alias new_no_dup new
def new(str)
new_no_dup(str.dup)
end
end
def initialize(str)
@str = str
end
...
end
任何人都可以准确解释这里发生了什么吗?我理解到班级<< self 部分,但我不太明白将 new 方法别名为 new_no_dup ,只是在下面的新方法中调用它?另外,你认为作者为什么要这样做?
I was looking through some code in a string escape library the other day and I came across some code that looks like this:
class StringWrapper
class << self
alias new_no_dup new
def new(str)
new_no_dup(str.dup)
end
end
def initialize(str)
@str = str
end
...
end
Can anyone explain exactly what is going on here? I understand up to the class << self part, but I don't quite understand aliasing the method new to new_no_dup, only to call it in the new method below? Also, why do you think the author want to do this in this manner?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过将new_no_dup别名为new,可以通过调用new_no_dup来调用原来的新功能。
StringWrapper.new 方法对提供的字符串调用重复 (.dup),然后将该副本提供给原始 StringWrapper.new 方法。
至于为什么,我假设作者试图阻止原始字符串被更改。 StringWrapper 将始终在内存中拥有自己的字符串。
By aliasing new_no_dup to new, the original new functionality can be called by calling new_no_dup.
The StringWrapper.new method calls duplicate (.dup) on the provided string and then provides that copy to the original StringWrapper.new method.
As for why, I would assume the author is trying to prevent the original string from being changed. StringWrapper will always have it's own string in memory.
是否对字符串使用
.dup
会影响就地修改(以!
结尾的方法)是否影响原始字符串。作为一个愚蠢的小演示...
如果您运行相同的代码片段,将
local = s.dup
更改为local = s
,则greeting< 的最终值/code> 将是
"HI"
,因为shout
将修改greeting
。.dup
返回原始字符串的副本,防止对原始字符串进行修改。Whether you use
.dup
on strings influences whether in-place modifications (methods ending with!
) affect the original string.As a silly little demonstration...
If you run the same snippet, changing
local = s.dup
tolocal = s
, then the final value ofgreeting
will be"HI"
becauseshout
will have modifiedgreeting
..dup
returns a copy of the original string, preventing modifications to the original.