Created
March 30, 2012 20:19
-
-
Save mkoby/2254679 to your computer and use it in GitHub Desktop.
Intro to Ruby - 07 - Classes: Part 01
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
## This is a basic Ruby class | |
class Employee | |
end | |
## We can create an object from this class | |
e = Employee.new # => #<Employe:0x37978873> #Or some other gibberish |
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
## Classes can have properties, like name, age, etc | |
## properties can have 1 of three levels of access | |
## | |
## attr_reader - read only, can't write | |
## attr_writer - write only, can't read | |
## attr_accessor - both read and write | |
## | |
## These access levels are for the USER of the class, | |
## you will have FULL access to the properties INSIDE | |
## the class. | |
class Employee | |
attr_accessor :name | |
attr_reader :age | |
attr_writer :salary | |
end | |
e = Employee.new | |
## The name property is both read and write | |
e.name = "Michael Koby" # => "Michael Koby" | |
e.name # => "Michael Koby" | |
## The age property is read only so we can't set it | |
e.age = 32 # => NoMethodError | |
## The salary method is writable but not readable | |
## so we can set it, but we can't read its value | |
e.salary = 30000 # => 30000 | |
e.salary # => NoMethodError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment