Skip to content

Instantly share code, notes, and snippets.

@mkoby
Created April 9, 2012 16:36
Show Gist options
  • Save mkoby/2344615 to your computer and use it in GitHub Desktop.
Save mkoby/2344615 to your computer and use it in GitHub Desktop.
Intro to Ruby - 09 - Methods in Classes
class Employee
attr_accessor :name
def self.new_with_name(name)
output = self.new
output.name = name
return output
end
end
# List all methods on the employee class and sort them
Employee.methods.sort
=> [... "new_with_name", ...]
# Use the class method to create a new employee with a name
e = Employee.new_with_name(“Michael Koby”)
e.name # => "Michael Koby"
# List all methods available on the object created with the class method
e.methods.sort
=> [...] #doesn't contain the new_with_name method because it's a CLASS method
class Employee
attr_reader :salary
def initialize(name, salary)
@name = name
@salary = salary
end
def give_raise(percentage)
@salary *= (1 + percentage)
@salary = @salary.to_i
end
end
# Initialize new object
e = Employee.new(“Michael Koby”, 50000)
# Call instance method "give_raise"
e.give_raise(0.05) # => 52500
# Check that the salary is the newer number
e.salary # => 52500
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment