Ruby for Rails book question

The book says that it is possible to define a method twice and the last definition over-rides
previous definitions.

But it does not explain why we might need to do this. Any ideas on scenario where this might be
helpful? TIA.

Bala Paranj wrote:

The book says that it is possible to define a method twice and the last definition over-rides
previous definitions.

But it does not explain why we might need to do this. Any ideas on scenario where this might be
helpful? TIA.

>

Loads of occasions. I've just used it to give a method to a parent STI
class, which is therefore the default method for all children. However,
one of the child classes redefines that method because it needs to
behave in a different way just for that child class. Once you get used
to it, it's tremendously powerful.

HTH
CT

I understand about the inheritance. Here is the section that is confusing:

Redefining methods
Nothing stops you from defining a method twice, or overriding it:
class C
  def m
    puts "First definition of method m"
  end
  def m
    puts "Second definition of method m"
  end
end
What happens when we call m on an instance of C? Let’s find out:
C.new.m
The printed result is Second definition of method m. The second definition has
prevailed: We see the output from that definition, not from the first. When you
override a method, the new version takes precedence.

Is there any real-life scenario for its use?

Hi --

You wouldn't literally define a method twice in a row like that... but
there are scenarios -- other than inheritance -- where you might
redefine a method.

Like, say you're using a plugin such as LoginEngine. Maybe the
controller methods provided don't do quite what you want. You can
define your own UserController which has the same methods as
LoginEngine's UserController. You're not subclassing, and you're not
replacing the whole UserController class -- just the methods with the
same names will be overwritten.

Make sense?

Do you mean you would open the class and define the same method with custom implementation? That
is not the same as defining within the same class. If you could modify that class, why not just
delete the old method implementation? It's not being used so we keep the junk code around?