Reputation: 33
Here I declare instance variable as global. In the input statement, I'm not getting output "home/abc.txt"
. What is the syntax to access instance variable inputs?
class AbcController
@filename = 'home/abc.txt'
def querypass
puts @filename
end
...
end
Upvotes: 1
Views: 102
Reputation: 44685
When declared like that, @filename
asssignment is run in context of the class and is sth called class instance variable. querypass
method is defined on class instance and has no access to it. Probably what you want to do is:
class AbcController
def initialize
@filename = 'home/abc.txt'
end
def querypass
puts @filename
end
...
end
In this case each instance will have its own copy of the variable and each of them will start with same initial value. However, if you really want to have a single variable for the whole class, you can do:
class AbcController
class << self
attr_accessor :filename # or attr_reader
end
@filename = 'home/abc.txt'
def querypass
puts self.class.filename
end
...
end
Or if you don't want to create any class setter or reader:
class AbcController
@filename = 'home/abc.txt'
def querypass
puts self.class.instance_variable_get(:@filename)
end
...
end
Upvotes: 2