Friday 10 June 2016

Open Class Definitions and Method Aliasing


Hi readers,

In this post we are going to learn how to open existing class defination and alias the method which is exist already in the class.

Open Class Definitions and Method Aliasing:

    class Peter 
      def say_hi 
        puts "Hi" 
      end 
    end 
     
    class Peter 
      alias_method :say_hi_orig, :say_hi 
      def say_hi 
        puts "Before say hi" 
        say_hi_orig 
        puts "After say hi" 
      end 
    end 
     
    Peter.new.say_hi  

Core Classes are Also Open:

 class Integer
  def even?
    (self % 2) == 0
  end
end
 
p (1..10).select { |n| n.even? } # => [2, 4, 6, 8, 10] 

Hope you understand the concept and you will practice this.
Thanks for reading this, if like share this.

No comments:

Post a Comment

My Experience in RUBYCONF INDIA 2016

Hi Readers, Rubyconf India is a global event complementing other RubyConf events across the world. I attended this event held on 19-20 ma...