1

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).

Makoto
  • 104,088
  • 27
  • 192
  • 230
Roman A. Taycher
  • 18,619
  • 19
  • 86
  • 141
  • 1
    Possible duplicate: [Does Ruby have a method_missing equivalent for undefined instance variables?](http://stackoverflow.com/questions/7651213/does-ruby-have-a-method-missing-equivalent-for-undefined-instance-variables) – rdvdijk Oct 06 '11 at 07:58
  • I don't have any plans to use this in production – Roman A. Taycher Oct 06 '11 at 08:01

2 Answers2

1

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.

Carl Suster
  • 5,826
  • 2
  • 22
  • 36
  • The behavior I am seeing is that method_missing is not being called when I try to access an attribute that is undefined, it just directly evaluates as Nil without being intercepted. Am I missing something? – Sam Woods Sep 21 '16 at 17:51
0

you could write a wrapper method

def something
  @var || "your default"
end
Omar Qureshi
  • 8,963
  • 3
  • 33
  • 35