Polymorphism in Ruby

by Ahmad hamza (@ahmad_719

What is Polymorphism?

What if 'CUT' is being said to these people?

The Surgeon

The Hair Stylist

The provision of a single interface to entities of different types

Inheritance

By inheritance we can achieve polymorphism

Duck Typing

When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.

1.to_i    #=> Fixnum
"1".to_i  #=> Fixnum 

You should treat objects according to the methods they define,

rather than the classes from which they inherit or the modules they include.

Decorator Pattern

The decorator pattern is used to extend the functionality of a certain object in a runtime. In a statically typed language you need to define decorator interface, then subclass from it and initialize the component (object) that you are decorating.

Replace conditional statements

Subtitle

class Parser
  def parse(type)
    puts 'The Parser class received the parse method'

    if type == :xml
      puts 'An instance of the XmlParser class received the parse message'
    elsif type == :json
      puts 'An instance of the JsonParser class received the parse message'
    end
  end
end

Thank You

Polymorphism in Ruby

By Ahmad Hamza

Polymorphism in Ruby

About polymorphism and ways to solve the problem in Ruby

  • 1,186