Skip to content

Instantly share code, notes, and snippets.

@mkoby
Created April 9, 2012 16:56
Show Gist options
  • Save mkoby/2344717 to your computer and use it in GitHub Desktop.
Save mkoby/2344717 to your computer and use it in GitHub Desktop.
Intro to Ruby - 10 - Classes: Putting it All Together
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
# 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