lyen lyen - 3 months ago 7
Ruby Question

Defining a method that checks the existence of a variable

Is it possible to define a method

a?
which returns
true
when
a
exists, and returns
false
when
a
is not defined?

The following code doesn't work, because when
defined? a
got executed, variable
a
is outside of its scope.

a = 123

def a?
if defined? a
return true
else
return false
end
end

puts a? # false


Is it possible to make the last line of my code return
true
?

Answer

In ruby, the keyword def acts a scope gate, so you lose access to local variables that are defined outside of the method definition. Alternatively, you can define methods using a block, allowing you access to variables defined outside of the method definition.

a = '123'

define_method 'a?' do 
  defined? a
end

For more information on this, I highly recommend reading through the first section of Metaprogramming Ruby

Comments