Search code examples
rubyinstance-variables

hash[key] is to hash.fetch(key) as @ivar is to what?


To expand on the title: How can I access an instance variable (@ivar) in a way that results in an exception if the instance variable hasn't been initialized?


Solution

  • There is no built in method that provides this functionality in respect to instance variables, however;

    Since Hash#[] is analogous to @ivar (or instance_variable_get(:@ivar)) in your example then Hash#fetch would be analogous to

    def instance_variable_fetch(sym)
      raise(NameError, "instance variable not found: #{sym}") unless instance_variable_defined?(sym) 
      instance_variable_get(sym)
    end 
    

    Example:

    @var = 42
    instance_variable_fetch(:@var)
    #=> 42
    @ivar = nil
    instance_variable_fetch(:@ivar)
    #=> nil
    instance_variable_fetch(:@other_var)
    #=> NameError: instance variable not found: @other_var