0

当我在 irb 中执行以下操作时,我得到以下输出:

>> class TestMe
>>   def new
>>     puts 'hi!'
>>   end
>> end
=> nil
>> TestMe.new.new
hi!

此外:

>> class TestMe
>> end
=> nil
>> TestMe.new.new
NoMethodError: undefined method `new' for #<TestMe:0x00000101038750>

但是当我在我选择的文本编辑器中编写一些代码时,它调用了一个名为new(但不是实例化新对象的Object方法)的实例方法,它会像保留关键字一样突出显示:newnew

@page = current_user.locations.new

请注意,locations这里返回一个委托类,该类执行一些繁重的工作(通过此new方法)并最终返回一个Location.new实例,其中包含一些准备就绪的基本设置数据,但new它本身并没有在类对象上被调用。这是方法名称的可接受使用还是我会遇到问题?

4

1 回答 1

3

The first call to .new will invoke the constructor, and return an instance of your class. The second call to .new will invoke an instance method on that object. It's completely acceptable to define a new instance method.

In order to interfere with the constructor, you would have to define a class-level method called new. That method can invoke super#new (which invokes Class#new) to perform the actual creation of the object:

class Test
  def self.new
    puts "hi!"
    super
  end
end


x = Test.new # outputs "hi"

It's completely valid to overwrite new at both an instance and class level, so long as you define your custom new method to do something sane.

于 2012-10-26T19:01:57.660 回答