I found an interesting problem: http://rubeque.com/problems/fixing-bad-code-the-wrong-way/solutions
Generally we have a simple class (notice that we don’t have attr_accessor here):
class Foo
def itnialize(name)
self.foo = name
end
def set_bar
self.bar = 'it will fail..'
end
end
I thought that ruby will raise no method error when I call Foo.new but it passes without any problems. The code will fail when I try Foo.new.bar
How is it possible and how to access Foo.new.foo variable?
You have a typo and have miss-spelt
initializeasitnializeso it won’t be being called – so no error.It looks like you’re trying to create an instance variable – to do so you need, somewhere, to define it with the
@prefix. So you might do:which would then mean you are able to access
@fooinside the class.self.foocan only ever refer to a methodfoo, so you need to define that method if you want to call it, either explicitly or by using one of theattrvariants.However, in this case, you could just do