Created
April 29, 2009 14:45
-
-
Save semanticart/103825 to your computer and use it in GitHub Desktop.
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
# 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