Created
April 9, 2012 16:56
-
-
Save mkoby/2344717 to your computer and use it in GitHub Desktop.
Intro to Ruby - 10 - Classes: Putting it All Together
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 Employee | |
attr_accessor :name, :age | |
attr_reader :salary, :department | |
initialize(name = “”, salary = 0, department = “”) | |
@name = name | |
@salary = salary | |
@department = department | |
end | |
def set_new_salary(salary) | |
@salary = salary | |
end | |
def change_department(new_department) | |
@department = new_department | |
end | |
def give_raise(percentage) | |
@salary *= (1 + percentage) | |
@salary = @salary.to_i | |
end | |
def to_s | |
“#{@name}\t#{@age}\t#{department}\t#{salary}” | |
end | |
end |
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
# Create employee from our new Employee class | |
e = Employee.new(“Michael Koby”, 55000, “Dev”) | |
# Use change_department method | |
e.change_department “IT” | |
# Verify the department changed | |
e.department # => "IT" | |
# Give the employee a raise, via the give_raise method | |
e.give_raise(0.08) # => 59400 | |
# Set the employee's age | |
e.age = 32 # => 32 | |
# Output nice tab delimited output to screen using the to_s method | |
puts e.to_s | |
#Result: Michael Koby 32 IT 59400 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment