开发者

What monkeypatch creates the private method split?

开发者 https://www.devze.com 2023-02-27 03:54 出处:网络
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

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 pr开发者_如何学Pythonint and puts)? If so, what added it, and why did they use a method name that already exists for String?


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>'
0

精彩评论

暂无评论...
验证码 换一张
取 消