什么 Monkeypatch 创建了私有方法 split?

发布于 2024-11-01 19:04:26 字数 529 浏览 7 评论 0 原文

问题 Ruby:调用 3:Fixnum 的私有方法私有方法`split'调用nil:NilClass (NoMethodError) 分别提到 FixnumNilClass 对象的私有方法 split

这个私有 split 方法是猴子补丁的伪关键字(如 printputs)吗?如果是这样,是什么添加了它,为什么他们使用 String 已经存在的方法名称?

The questions Ruby: Private method called for 3:Fixnum and private method `split' called for nil:NilClass (NoMethodError) mention private methods split for Fixnum and NilClass objects respectively.

Is this private split method a monkeypatched pseudo-keyword (like print and puts)? If so, what added it, and why did they use a method name that already exists for String?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

为你拒绝所有暧昧 2024-11-08 19:04:26

您可以自己解决这个问题(即使不阅读其他答案):

ruby-1.8.7-p330 :001> 3.method(:split)
#=> #<Method: Fixnum(Kernel)#split> 

您可以从我的 Ruby Method Lookup FlowPDF 版本)所有对象的方法都在实例方法处完成对象...它本身包括内核。因此,Kernel 的所有实例方法(添加了许多可用作顶级便利方法的情况)也最终成为每个对象上的方法。

请注意,在 1.9+ 中情况并非如此,因为 Kernel#split 已被删除:

ruby-1.9.1-p378 :001> 3.method(:split)
#=> NameError: undefined method `split' for class `Fixnum'
#=>     from (irb):1:in `method'
#=>     from (irb):1
#=>     from /Users/phrogz/.rvm/rubies/ruby-1.9.1-p378/bin/irb:16:in `<main>'

You can solve this yourself (even without reading the other answer):

ruby-1.8.7-p330 :001> 3.method(:split)
#=> #<Method: Fixnum(Kernel)#split> 

You can see from my Ruby Method Lookup Flow (PDF version) that methods for all objects finish at the instance methods of Object…which itself includes Kernel. Thus, all instance methods of Kernel (added many cases to be available as top-level convenience methods) also end up as methods on every object.

Note that this is not true in 1.9+ as Kernel#split has been removed:

ruby-1.9.1-p378 :001> 3.method(:split)
#=> NameError: undefined method `split' for class `Fixnum'
#=>     from (irb):1:in `method'
#=>     from (irb):1
#=>     from /Users/phrogz/.rvm/rubies/ruby-1.9.1-p378/bin/irb:16:in `<main>'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文