Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
self vs instance vs local variables in initialize
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