Skip to content

Instantly share code, notes, and snippets.

@sdball
Created May 1, 2014 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdball/89f18549090496d97c66 to your computer and use it in GitHub Desktop.
Save sdball/89f18549090496d97c66 to your computer and use it in GitHub Desktop.
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