Skip to content

Instantly share code, notes, and snippets.

@josh7weaver
Last active August 29, 2015 14:13
Show Gist options
  • Save josh7weaver/7a3d8b524aa70adc4e27 to your computer and use it in GitHub Desktop.
Save josh7weaver/7a3d8b524aa70adc4e27 to your computer and use it in GitHub Desktop.
Example of Ruby OOP
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
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
@josh7weaver
Copy link
Author

Notes

  • Person has getters and setters by same name as the attribute for firstname and lastname
  • Person has only a getter (fullname) for fullname. in php it would be Person->getFullname();
  • Person.fullname = "junk" throws error bc there's no setter defined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment