Hsiu Chuan Tsao
Hsiu Chuan Tsao

Reputation: 1566

How is the ruby's extend syntax work?

I write two kind syntax for extend, but is appear different behavior,one return 50, the other return 70, anyone can explain why?

module Discount
  def cost
    super + 20
  end
end

class Toy
  extend Discount
  def cost
    50
  end
end

# check
Toy.new.cost #=> 50

But:

module Discount
  def cost
    super + 20
  end
end

class Toy
  def cost
    50
  end 
end

# check
Toy.new.extend(Discount).cost #=>70

Upvotes: 1

Views: 186

Answers (2)

Alireza Bashiri
Alireza Bashiri

Reputation: 452

Object#extend is simply shortcut that includes a module in the receiver's eigenclass.

for further information about eigenclasses go to https://en.wikipedia.org/wiki/Metaclass#In_Ruby

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

In the first snippet you call extend during class declaration, i. e. on Toy object, which is apparently a class. It is the same as calling Toy.extend(Discount).

In the second snippet you extend the Toy.new, which is apparently a Toy instance.

Upvotes: 2

Related Questions