Ruby - Overriding Existing Methods

Introduction

Ruby can override existing classes and methods.

For example, consider Ruby's String class.

If you create a string, you end up with an object of class String; for example:

Demo

x = "This is a test" 
puts x.class

Result

You can call a number of different methods upon the String object stored in x:

Demo

x = "This is a test" 
puts x.length 
puts x.upcase

Result

You can override the length method of the String class:

Demo

class String 
  def length #  ww  w  . jav  a 2 s .  c  om
    20 
  end 
end 

puts "This is a test".length 
puts "a".length 
puts "A really long line of text".length

Result

Related Topics