What is duck typing in ruby?

Starting out in ruby duck typing is one of those concepts you will hear thrown around. It really is a simple concept to understand. Have no fear! A beer example is here!

class Tinseth  
  def calculate_ibus
    puts "lets calculate ibus with tinseth!"
  end
end

class Rager  
  def calculate_ibus
    puts "lets calculate ibus with rager!"
  end
end

class Ibu  
  def calculate_ibus(type)
    type.calculate_ibus
  end
end  

Now we can do something like this:

ibu = Ibu.new  
ibu.calculate_ibus(Tinseth.new)

ibu = Ibu.new  
ibu.calculate_ibus(Rager.new)  

Running the above will get you output like this below:

lets calculate ibus with tinseth!

lets calculate ibus with rager!  

The calculate_ibus method reacts differently depending on the object that receives the message.

And guess what? This is one way to implement polymorphism!

Want to learn about polymorphism? Maybe polymorphic associations in rails? Yeah? Here ya go!

What are polymorphic associations in rails?