Last active
August 29, 2015 14:22
-
-
Save nickmalcolm/cb90e8479bc55b486aac to your computer and use it in GitHub Desktop.
Ruby Instance Variables vs Local Variables, and overriding getters / setters
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
# Shows the diffference of calling methods different ways | |
class Foo | |
# attr_accessor defines def bar;end and def bar=(val);end | |
attr_accessor :bar | |
def initialize | |
self.bar = "hello" | |
end | |
def method_one | |
puts bar # "hello" (instance attr) | |
bar = "cheese" # creates local var | |
puts self.bar # "hello" (instance attr via method) | |
puts @bar # "hello" (explicit instance attr) | |
puts bar # "cheese" (local var) | |
end | |
def method_two | |
self.bar = "hello" # instance attr assign via method | |
puts self.bar # "hello" (instance attr via method) | |
puts @bar # "hello" (explicit instance attr) | |
puts bar # "hello" (instance attr) | |
end | |
def method_three | |
@bar = "hello" # explicit instance attr assign | |
puts self.bar # "hello" (instance attr via method) | |
puts @bar # "hello" (explicit instance attr) | |
puts bar # "hello" (instance attr) | |
end | |
def method_four | |
puts asd # NameError: undefined local variable or method `asd' | |
end | |
def method_five | |
puts @asd # nil | |
end | |
end | |
# Middle aged person lies about their age | |
class MiddleAgedLiar | |
attr_accessor :age | |
def age | |
@age - 10 | |
end | |
def method_one | |
self.age = 45 | |
puts age # 35 | |
puts self.age # 35 | |
puts @age # 45 | |
end | |
end | |
# Taxed person always gets less money in the bank than they deposit | |
class TaxedPerson | |
attr_accessor :bank_balance | |
def initialize | |
# If we initialized using self.bank_balance, people would be born with $-1 | |
@bank_balance = 0 | |
end | |
def bank_balance=(val) | |
@bank_balance = val - 1 | |
end | |
def method_one | |
self.bank_balance = 10 | |
puts bank_balance # 9 | |
puts self.bank_balance # 9 | |
end | |
def method_two | |
@bank_balance = 10 | |
puts bank_balance # 10 | |
puts self.bank_balance # 10 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment