Home > Enterprise >  Calling super, super class method with parameters in Ruby
Calling super, super class method with parameters in Ruby

Time:03-02

I found the below working solutions (link 1, link 2) which call the grandparent method but without any parameters. Does anyone know how to call the grandparent method with parameters?

class GrandParent
  def fun(word)
    puts word
  end
end

class Parent < GrandParent
  def fun(word)
    puts word   'end'
  end
end

class Child < Parent
  def fun(word)
    GrandParent.instance_method(:fun).bind(self).call
  end
end

CodePudding user response:

You can pass parameters directly to call like this:

class Child < Parent
  def fun(word)
    GrandParent.instance_method(:fun).bind(self).call(param1, param2)
  end
end

CodePudding user response:

call accepts parameters

GrandParent.instance_method(:fun).bind(self).call word

I don't know your use case, but this is a Really Bad Idea™. It creates unnecessary dependencies directly between Child and GrandParent such that all kinds of normally reasonable refactoring would result in a crash e.g. moving fun to only be implemented in Parent, changing Parent to subclass a different but similar parent, etc.

  •  Tags:  
  • ruby
  • Related