“初始化程序=新配置”有什么作用?

时间:2013-01-12 17:51:15

标签: ruby

initializer = new configuration做了什么?

def self.run(configuration = Configuration.new)
  yield configuration if block_given?
  initializer = new configuration
  initializer.
  initializer
end

2 个答案:

答案 0 :(得分:2)

让我们逐步介绍这些内容。

# It is a definition of a class method which takes one argument
# with a default value.    
def self.run(configuration = Configuration.new)
  # It passes the argument to a block if one was given.
  yield configuration if block_given?
  # It calls method `new` passing the `configuration` as
  # an argument. The returned value is saved in the local
  # variable.
  initializer = new configuration
  # Two following lines are a single expression: a call
  # to method `initializer` of the object pointed to by the
  # variable `initializer`, i.e.
  # 
  #   initializer.send :initializer
  # 
  # No idea why one would break this expression into two lines.
  # The value returned from the call to `initializer` becomes
  # the return value of the analysed method.
  initializer.
  initializer
end

答案 1 :(得分:0)

该代码的上下文可能类似于:

class MyClass
  def self.run
  ....

所以自我是MyClass。写newself.new的快捷方式,这意味着MyClass.new只会创建一个新的类实例。