代码之家  ›  专栏  ›  技术社区  ›  krunal shah

与超级混为一谈

  •  0
  • krunal shah  · 技术社区  · 14 年前

    重写为xml。

    这些代码之间有什么区别。有人能用恰当的例子来解释吗?

    一。

    def to_xml(options = {})
      options.merge!(:methods  => [ :murm_case_name, :murm_type_name ])
      super
    end
    

    2。

    def to_xml(options = {})
      super
      options.merge!(:methods  => [ :murm_case_name, :murm_type_name ])
    end
    
    2 回复  |  直到 14 年前
        1
  •  4
  •   Andrew Grimm atk    14 年前

    tl;博士: super 行为方式出人意料,变量很重要,而不仅仅是对象。

    什么时候? 超级的 是调用的,不是用传入的对象调用的。

    它是用被调用的变量调用的 options 打电话的时候。例如,使用以下代码:

    class Parent
      def to_xml(options)
        puts "#{self.class.inspect} Options: #{options.inspect}"
      end
    end
    
    class OriginalChild < Parent
      def to_xml(options)
        options.merge!(:methods  => [ :murm_case_name, :murm_type_name ])
        super
      end
    end
    
    class SecondChild < Parent
      def to_xml(options)
        options = 42
        super
      end
    end
    
    begin
      parent_options, original_child_options, second_child_options = [{}, {}, {}]
      Parent.new.to_xml(parent_options)
      puts "Parent options after method called: #{parent_options.inspect}"
      puts
      OriginalChild.new.to_xml(original_child_options)
      puts "Original child options after method called: #{original_child_options.inspect}"
      puts
      second_child_options = {}
      SecondChild.new.to_xml(second_child_options)
      puts "Second child options after method called: #{second_child_options.inspect}"
      puts
    end
    

    产生输出

    Parent Options: {}
    Parent options after method called: {}
    
    OriginalChild Options: {:methods=>[:murm_case_name, :murm_type_name]}
    Original child options after method called: {:methods=>[:murm_case_name, :murm_type_name]}
    
    SecondChild Options: 42
    Second child options after method called: {}
    

    你可以看到 SecondChild 使用变量调用super方法 选项 指的是 Fixnum 价值 42 ,而不是最初由 选项 .

    使用 options.merge! ,您将修改传递给您的哈希对象,这意味着变量引用的对象 original_child_options 现在被修改了,可以在 Original child options after method called: {:methods=>[:murm_case_name, :murm_type_name]} 行。

    (注:我改了 选项 第二胎42岁,而不是打电话 Hash#merge ,因为我想展示的不仅仅是物体的副作用)

        2
  •  2
  •   shingara    14 年前

    第一个返回超级调用的结果。所以就好像你从来没有对你的案子感兴趣一样。

    第二次在你改变之前呼叫super,然后再改变选项。

    我想你真的想:

    def to_xml(options = {})
      super(options.merge!(:methods  => [ :murm_case_name, :murm_type_name ]))
    end