Created
May 8, 2013 22:12
-
-
Save carlossanchezp/5544075 to your computer and use it in GitHub Desktop.
Ruby OOP examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment