Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Binding#local_variable_defined?
(::interned varname) -> bool
binding.local_variable_defined?(symbol) → obj
proc.c
View on GitHub ↗
static VALUE
bind_local_variable_defined_p(VALUE bindval, VALUE sym)
{
ID lid = check_local_id(bindval, &sym);
const rb_binding_t *bind;
const rb_env_t *env;
if (!lid) return Qfalse;
if (rb_numparam_id_p(lid)) {
rb_name_err_raise("numbered parameter '%1$s' is not a local variable",
bindval, ID2SYM(lid));
}
GetBindingPtr(bindval, bind);
env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
return RBOOL(get_local_variable_ptr(&env, lid, TRUE));
}
Returns true if a local variable symbol exists.
Example
def foo a = 1 binding.local_variable_defined?(:a) #=> true binding.local_variable_defined?(:b) #=> false end
This method is the short version of the following code:
Example
binding.eval("defined?(#{symbol}) == 'local-variable'")
Ruby version changes
-
4.0
-
Binding#local_variablesdoes no longer include numbered parameters. Also,Binding#local_variable_get,Binding#local_variable_set, andBinding#local_variable_defined?reject to handle numbered parameters. [Bug #21049]
-
See also
#implicit_parameters
#local_variable_get
#implicit_parameter_get
#local_variables
also in
4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0