Skip to content

Instantly share code, notes, and snippets.

@phstc phstc/happy_oop.rb
Created Oct 26, 2010

Embed
What would you like to do?
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
You can’t perform that action at this time.