ruby 中改进和重新定义 class 之间的区别

Difference between Refinements and redefine class in ruby

我正在阅读一些关于 ruby 编程语言的书,想知道这样的东西是如何工作的

class String
  def word_count
    frequencies = Hash.new(0)
    downcase.scan(/\w+/) { |word| frequencies[word] += 1 }
    return frequencies
  end
end

我知道有一个内置字符串,我来自 (C++) 顺便说一句,所以创建 class string 会在定义对象 string x = new string() 时产生歧义,我搜索了一下,发现一些概念被命名为 refinement,它允许我们修改和添加函数到 String class,我看到他们使用关键字 refine 来制作这些东西(根据文档) ,但是我的问题来了,当我把上面的 class 放在 irb 上并开始像那样测试它时 "amr adel".word_count,它给了我正确的结果,我预计不会工作首先,如果它有效,为什么我什至可以在我的代码中使用 refine 为什么我不只创建一个与内置函数同名的 class 并添加附加函数和修改函数,这种方式是否隐含地进行了细化过程?

我承认 ruby 很棒而且很容易使用,但我想知道事情的进展。

如果您能参考一些文章或其他东西,将不胜感激 谢谢

来自the ruby documentation

You may activate refinements at top-level, and inside classes and modules. You may not activate refinements in method scope. Refinements are activated until the end of the current class or module definition, or until the end of the current file if used at the top-level.

改进的整点(与仅仅扩展核心class相反)是它们是范围

在您上面的代码中,String#word_count 将被定义为 无处不在 - 例如,如果您有多个文件。

另一方面,如果您将该方法定义为细化,那么它只会在您明确using的地方定义它。

这样做的动机是您可以 add/alter 在一个位置执行行为而不影响其他地方的代码。