Say if I want to return something else if a variable isn't initialized instead of nil
. Is this possible? I'd like to only overload it per class, not globally.
(The reason for this is mainly to play with crazy tricks).
Say if I want to return something else if a variable isn't initialized instead of nil
. Is this possible? I'd like to only overload it per class, not globally.
(The reason for this is mainly to play with crazy tricks).
In that case, you could use #instance_variable_defined?
and #instance_variable_get
. For instance:
class Thing
def method_missing(method, *args, &block)
ivar_name = "@#{method}".intern
if instance_variable_defined? ivar_name
instance_variable_get ivar_name
else
super method, *args, &block
end
end
end
would automatically define instance variable readers for any set instance variables, or:
class Thing
IVARS = [:@first, :@second]
def method_missing(method, *args, &block)
ivar_name = "@#{method}".intern
if IVARS.include? ivar_name
if instance_variable_defined? ivar_name
instance_variable_get ivar_name
else
"your default"
end
else
super method, *args, &block
end
end
end
would define readers for any if the instance variables named in the IVARS
constant, defaulting to the default value. I'm sure you can see how you could change that to be a hash mapping instance variable names to their default values or whatever.
Or you could simply use instance_variable_get
to provide a default value if you don't need any more flexibility than this:
thing = Thing.new
thing.instance_variable_get :@ivar_name, "your default"
although this would not define reader methods - you would have to access via instance_variable_get
each time.
you could write a wrapper method
def something
@var || "your default"
end