Skip to content

Instantly share code, notes, and snippets.

@ashgti
Forked from semanticart/gist:103825
Created April 29, 2009 23:16
Show Gist options
  • Save ashgti/104134 to your computer and use it in GitHub Desktop.
Save ashgti/104134 to your computer and use it in GitHub Desktop.
# thanks to @judofyr for explaining this to me like thus:
# when ruby sees "bar =" (even thought it's not eval'd) it creates a local variable and assigns it to nil.
# so the first "bar" is a method call, while the second is a local variable. it should work if you replace
# it with "self.bar".
class Foo
attr_accessor :bar, :id
def initialize id
@id = id
end
def test
puts "bar was '#{bar}'"
unless id
raise "id is nil or false"
bar = "this should not be"
end
puts "bar is now '#{bar}'"
end
def proper
puts "bar was '#{@bar}'"
unless id
raise "id is nil or false"
@bar = "this should not be"
end
puts "bar is now '#{@bar}'"
end
end
foo = Foo.new(1)
foo.bar = "pants"
foo.test
puts "---"
foo.proper
#output:
# bar was 'pants'
# bar is now ''
# ---
# bar was 'pants'
# bar is now 'pants'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment