fetch(name, default)
fetch(name, &block)

Although you'll typically access variables just by referring to them by name (like local variables), sometimes you want to programmatically query a variable, or get a default value for a variable if the variable has not been set. In these cases, fetch can help you.


When invoked with just the variable name to query, it acts much like accessing a variable by name, or by using the square brackets on a configuration instance:

[[set] :user, "bob"
p user         #--> prints "bob"
p self[:user]  #--> prints "bob"
p fetch(:user) #--> prints "bob"

However, if the variable does not exist, fetch will raise an IndexError exception (just as Hash#fetch does).

unset :user
p user         #--> raises NameError
p self[:user]  #--> prints nil
p fetch(:user) #--> raises IndexError

If you give a default value as the second argument, fetch will return that default value (instead of raising an exception) if the variable does not exist:

unset :user
p fetch(:user, "jim") #--> prints "jim"

Lastly, instead of a default value you can give a block, which will be called if the variable does not exist. The result of the block will be returned in that case:

unset :user
p(fetch(:user) { puts "Enter your user name:"; gets.chomp }) #--> prints whatever the user enters at the prompt

Note that a variable that has been set to nil exists; it simply exists as a variable with a value of nil.

set :user, nil
p fetch(:user, "bob") #--> prints nil

Lastly, as described in set, if the value of a variable responds to the :call method, then :call will be invoked on it and the result cached. The result will then be returned as the value of this variable. (This lets you set Proc objects as the value of variables and have them evaluated when the variable is first requested.)

x = 0
set(:count) { x }
x = 100
p fetch(:count) #--> prints 100
x = 1000
p fetch(:count) #--> still prints 100



This should be a symbol naming the variable. As described above, if this variable does not exist, an IndexError exception will be raised unless a default valule is provided.


This is the value to return if the requested variable does not exist.


If the requested variable does not exist, the block will be called and the result returned. Note that, unlike giving a block to set, this value is not cached, and the variable will continue to be undefined.

See Also