Reputation: 285
class Test
options = Trollop::options do
opt :mode, "Select script mode", :default => 0
opt :net, "Internal IP range", :type => :string
end
@options = options
def test
pp @options
end
end
Why does @options
return nil
when I call test()
?
I've also tried setting @options
to instance when Trollop is first called. I need to be able to pass the options hash returned from Trollop into different methods in the class.
Upvotes: 0
Views: 269
Reputation: 288
You're adding a class instance variable, but when you reference it in the method, you're referencing what looks like an instance variable.
First, you might want to instead use a class variable rather than a class instance variable. There's some information on the distinction here.
class Test
@@options = Trollop::options do
opt :mode, "Select script mode", :default => 0
opt :net, "Internal IP range", :type => :string
end
def test
pp @@options
end
end
Test.test
The other option is to instantiate your class variable when initializing the test object, as below:
class Test
def initialize
@options = Trollop::options do
opt :mode, "Select script mode", :default => 0
opt :net, "Internal IP range", :type => :string
end
end
def test
pp @options
end
end
t = Test.new
t.test
Upvotes: 0
Reputation: 34338
If you really want to use a class instance variable for option storage then this would work:
class Test
@options = Trollop::options ...
class << self
attr_accessor :options
end
def test
pp Test.options
# or self.class.options
end
end
# And this will work too..
pp Test.options
Otherwise you might want to use a class variable @@options
or constant, like the other ones pointed out, instead.
Upvotes: 1
Reputation: 146261
As Tass points out, changing @options
to OPTIONS
is one way.
You could also use @@options;
it's a class variable in either context.
Upvotes: 0
Reputation: 21740
What you have here is a scoping issue. @options
in class context is an instance variable of the class. In test
, you access the instance variable @options
in the current instance. Try constants, aka OPTIONS
, which have lexical scoping. Maybe someone else knows of a cleaner solution to this.
Upvotes: 0