Zack
Zack

Reputation: 2208

Mechanism of overridding methods in a Ruby class

Suppose I want to override a method of an existing class Array as below.

class Array
  def to_s
    self.join(',')
  end
end

So my question is - How does this overriding work? Does this add this definition of method to_s to the class Array? I mean if the class contained 'n' method definitions, it would now contain 'n+1' method definitions. Also, is it that there are two definitions of to_s method and the one that is added last is the one that would work?

Thanks.

Upvotes: 0

Views: 32

Answers (1)

Nick Veys
Nick Veys

Reputation: 23939

You aren't overriding the method, you are re-defining it. The one that was there is gone, replaced with what you put in. This is a risky thing to do w/the standard libraries, you don't know what behavior other code is relying upon.

You can try it w/your own class.

class Foo
  def bar
    puts 'One'
  end
end

class Foo
  def bar
    puts 'Two'
  end
end

Foo.new.bar
# Two

class Foo
  def bar
    puts 'Three'
    super
  end
end

Foo.new.bar
# Three
# test.rb:18:in `bar': super: no superclass method `bar' 
#   for #<Foo:0x007fd642029278> (NoMethodError)

Upvotes: 3

Related Questions