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
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]
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