Created
May 1, 2014 14:12
-
-
Save sdball/89f18549090496d97c66 to your computer and use it in GitHub Desktop.
self vs instance vs local variables in initialize
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 UsingSelf | |
attr_accessor :a, :b, :c | |
def initialize(a, b, c) | |
self.a = a | |
self.b = b | |
self.c = c | |
end | |
end | |
class UsingInstance | |
attr_accessor :a, :b, :c | |
def initialize(a, b, c) | |
@a = a | |
@b = b | |
@c = c | |
end | |
end | |
class UsingLocalVariablesIncorrectly | |
attr_accessor :a, :b, :c | |
def initialize(a, b, c) | |
a = a | |
b = b | |
c = c | |
end | |
end | |
using_self = UsingSelf.new('a', 'b', 'c') | |
puts using_self.a # => 'a' | |
puts using_self.b # => 'b' | |
puts using_self.c # => 'c' | |
using_self.c = 'see' | |
puts using_self.c # => 'see' | |
using_instance = UsingInstance.new('a', 'b', 'c') | |
puts using_instance.a # => 'a' | |
puts using_instance.b # => 'b' | |
puts using_instance.c # => 'c' | |
using_instance.c = 'see' | |
puts using_instance.c # => 'see' | |
using_local_variables_incorrectly = UsingLocalVariablesIncorrectly.new('a', 'b', 'c') | |
puts using_local_variables_incorrectly.a # => nil | |
puts using_local_variables_incorrectly.b # => nil | |
puts using_local_variables_incorrectly.c # => nil | |
using_local_variables_incorrectly.c = 'see' | |
puts using_local_variables_incorrectly.c # => 'see' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment