문제

The rules of Ruby's super keyword is that if it is called without arguments, all of the original arguments are forwarded. If it is called with explicit arguments, the explicit arguments are exclusively passed in.

In this example, arguments should never be forwarded, since I am calling super with exact arguments.

Example:

@doc = Nokogiri::HTML::DocumentFragment.parse("<body></body>")

class Cat < Nokogiri::XML::Node
  def initialize(arg1, arg2)
    super("cat", arg2) # Pass arg2 to super
    # Do something with arg1 later
  end
end

When calling: Cat.new("dog", @doc) I expect to get back a <cat></cat> tag, and I expect the first argument to be ignored. Instead I am getting a <dog></dog> tag.

Is there a reason this case would defy expected behavior?

도움이 되었습니까?

해결책

If you look at the source to nokogiri, it's actually the new method that sets the node's name, not the initialize method. Nothing mysterious is happening with regards to invoking super, it's just that the initialize method doesn't do anything with those arguments.

I assume this is because the new method is the one that is supposed to be allocating storage and so on for the object, which in nokogiri's case means creating the underlying libxml node, which is the thing that contain's the node's name.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top