So I’m using the awesome trollop gem to do option parsing, but I’m having a general problem with the scope of the variables it’s setting.
require 'trollop'
class MyClass
opts = Trollop::options do
opt :thing, "does something", default: "blah", type: String
end
def my_method
puts opts[:thing]
end
end
But I get:
undefined local variable or method `opts' for #<MyClass:0x0000010203c840> (NameError)
Any ideas what I’m doing wrong with my scope?
There are about six options here: instance variable, class instance variable, class variable, class constant, global variable, global constant. Which to use depends on your needs.
Instance Variable – each MyClass instance gets its own options:
Class Instance Variable – single value across the class that can be reassigned:
Class Variable – each MyClass and all subclasses share the same value (convenient syntax, but rarely a good idea):
Class Constant – single object that may be mutated, but not re-assigned. Easily accessed from this class, accessible from others via
MyClass::OPTS:Global Variable – you can only have one of these in your entire app; often global variables are ill-advised, but perhaps appropriate for a standalone application’s options:
Global Constant – accessed from many classes, can’t be set to a new value, but may be mutated: