Skip to content

Instantly share code, notes, and snippets.

@pauldowman
Created March 12, 2013 18:27
Show Gist options
  • Save pauldowman/5145517 to your computer and use it in GitHub Desktop.
Save pauldowman/5145517 to your computer and use it in GitHub Desktop.
Examples from today's class (class vs instance variables, initializers)
# Basic class with one attribute ("name")
class Person
attr_accessor :name
# line 2 is equivalent to lines 5 to 11:
# def name=(something)
# @name = something
# end
#
# def name
# return @name
# end
def say_name
puts name
end
end
x = Person.new
y = Person.new
x.name = "Paul"
y.name = "Will"
x.say_name
y.say_name
# Setting data on objects using an initializer (sometimes known as a
# "constructor function").
# Why do this?
# 1. This can guarantee that there is never a Person object with no name set
# 2. It's possible to make objects that can't be changed once created
# ("immutable").
# 3. More concise
class Person
def initialize(something)
@name = something
end
def say_name
puts @name
end
end
x = Person.new("Paul")
y = Person.new("Will")
x.say_name
y.say_name
class Person
def Person.set_max_class_size(n)
# max_class_size is a class variable, this is stored on the class itself,
# not on any of the instances (objects)
@@max_class_size = n
end
def Person.get_max_class_size
@@max_class_size
end
end
Person.set_max_class_size(24)
puts Person.get_max_class_size
x = Person.new x.set_max_class_size(10) # Error: an instance of Person doesn't have a method named
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment