需要帮助理解一些 Ruby 代码

发布于 2024-09-12 04:53:21 字数 360 浏览 3 评论 0原文

前几天我正在查看字符串转义库中的一些代码,我遇到了一些如下所示的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁吢 2024-09-19 04:53:22

通过将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.

九八野马 2024-09-19 04:53:22

是否对字符串使用 .dup 会影响就地修改(以 ! 结尾的方法)是否影响原始字符串。

作为一个愚蠢的小演示...

irb(main):009:0> def shout(s)
irb(main):010:1>  local = s.dup
irb(main):011:1>  local.upcase!
irb(main):012:1>  puts local
irb(main):013:1> end
=> nil
irb(main):014:0> greeting = "hi"
=> "hi"
irb(main):015:0> shout(greeting)
HI
=> nil
irb(main):016:0> greeting
=> "hi"

如果您运行相同的代码片段,将 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...

irb(main):009:0> def shout(s)
irb(main):010:1>  local = s.dup
irb(main):011:1>  local.upcase!
irb(main):012:1>  puts local
irb(main):013:1> end
=> nil
irb(main):014:0> greeting = "hi"
=> "hi"
irb(main):015:0> shout(greeting)
HI
=> nil
irb(main):016:0> greeting
=> "hi"

If you run the same snippet, changing local = s.dup to local = s, then the final value of greeting will be "HI" because shout will have modified greeting. .dup returns a copy of the original string, preventing modifications to the original.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文