Last active
August 29, 2015 14:13
-
-
Save josh7weaver/7a3d8b524aa70adc4e27 to your computer and use it in GitHub Desktop.
Example of Ruby OOP
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
require "person.rb" | |
person = Person.new({firstname: 'john', lastname: 'doe'}) | |
puts person.firstname # john | |
puts person.lastname # doe | |
# in php it would be person->getFullname(); | |
puts person.fullname # Mr. john doe | |
# in php its person->setFullname(); | |
person.fullname = "Abe Lincoln" # NoMethodError: undefined method `fullname=' <= this is a setter | |
person.prefix # NoMethodError: private method `prefix' called for #<Person:0x007fc74d949af0> | |
# MORE INFO | |
# | |
# Person#methods: firstname firstname= fullname lastname lastname= | |
# instance variables: @firstname @fullname @lastname |
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
class Person | |
# Attr_accessor creates instance variables for the class instance | |
# (i.e. @name, etc). | |
# AND creates GETTERS and SETTERS for all listed attributes (by the same name as the attribute) | |
attr_accessor :firstname, :lastname | |
# Attr_reader creates @fullname AND a getter ONLY | |
attr_reader :fullname | |
#this is equivalent to __construc() | |
def initialize(params) | |
@name = params[:firstname] | |
@lastname = params[:lastname] | |
@fullname = fullname | |
end | |
def fullname | |
# in php this would be: | |
# return _prefix() . " " . getFirstname() . " " . getLastname(); | |
return "#{prefix} #{firstname} #{lastname}" | |
end | |
private | |
#everything after this is private | |
def prefix | |
return "Mr." | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Notes
Person->getFullname();