Skip to content

Instantly share code, notes, and snippets.

@phstc
Created October 26, 2010 22:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phstc/647997 to your computer and use it in GitHub Desktop.
Save phstc/647997 to your computer and use it in GitHub Desktop.
Happy OOP examples using Ruby
#These Ruby OOP examples, are based on the Rails 3 presentation by @guilhermecaelum
class Person
#the attribute name is immutable
def initialize(name)
@name = name
end
def name
@name
end
end
pablo = Person.new('Pablo')
puts "pablo.name = #{pablo.name}"
#output
#pablo.name = Pablo
#overrides the method name only for the class INSTANCE scope
def pablo.name
@name.upcase
end
puts "pablo.name = #{pablo.name}"
#output
#pablo.name = PABLO
#overrides method name for the class scope
class Person
def name
@name.downcase
end
end
cantero = Person.new('Cantero')
puts "cantero.name = #{cantero.name}"
#output
#cantero.name = cantero
#YES... you also can change core classes like others classes
class String
#Added to_mussum for all strings instances
def to_mussum
self + 'zis'
end
end
puts 'Calcida'.to_mussum
#output
#Calcidazis
#'Multiple inheritance'
module Horse
def run
puts 'Inhhhhriiiii'
end
end
module Bird
def fly
puts 'Briiiihhhhh'
end
end
class Pegasus
include Horse
include Bird
end
pegasus = Pegasus.new
pegasus.run
pegasus.fly
#output
#Inhhhhriiiii
#briiiihhhhh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment