Docunext


Ruby Strings and Real Object Orientation

September 7th, 2009

Code:

barf = "hello"
puts barf
barf.upcase!
puts barf

Output:

ruby ruby-strings.rb
hello
HELLO

Pretty boring, huh? Well one of the nice things about Ruby is that you can do stuff like this:

class String
    def goodbye
        puts "Goodbye"
    end
end
barf = "hello"
puts barf
barf.upcase!
puts barf
barf.goodbye

Yes, very cool. What happened here was the function goodbye was added to the string class, so that every string object has access to it. Very very cool.

Related: Introduction to Ruby Modules

Yearly Indexes: 2003 2004 2006 2007 2008 2009 2010 2011 2012 2013 2015 2019 2020 2022