Web Development

Curiosity killed the cat

I have been working with Ruby for sometime now but haven’t checked things in a deeper sense. I wanted to experiment with method hierarchy especially when it comes to mixins.

Take this sample:

module Verb
  def eat(food)
    puts "Eating #{food} from model"
  end
end

class Dog
  include Verb
  def eat(food)
    puts "Eating #{food} from class"
  end
end

d = Dog.new
=> #<Dog:0x007fd675af6c18> 
d.eat('bone')
Eating bone from class

This simple example that Ruby methods in classes are valued more than methods in mixins. Thus module methods wouldn’t be seen if a class has a method with the same name.

module Verb
  def eat(food)
    puts "Eating #{food} from module"
  end
end

module AnotherVerb
  def eat(food)
    puts "Eating #{food} from second module"
  end
end

class Dog
  include Verb
  include AnotherVerb
end

d = Dog.new
=> #<Dog:0x007f8f639a97b0> 
d.eat('bone')
Eating bone from second module

The second example shows that the last loaded module takes precedence over previous ones. This is also seen here:

module Verb
  def eat(food)
    puts "Eating #{food} from module"
  end
end

module AnotherVerb
  def eat(food)
    puts "Eating #{food} from second module"
  end
end

class Dog
  include Verb
  include AnotherVerb
  include Verb
end

d = Dog.new
=> #<Dog:0x007fac1de1d388> 
d.eat('bone')
Eating bone from second module

It is very easy to assume that Eating bone from the module will be be the output. However, including the module a second time doesn’t affect which method is run since it does not recognize the second time it is loaded.

While these things aren’t particularly useful at this point, I just like experimenting about things.