Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Binding#local_variable_set
[U] (::interned varname, U obj) -> U
binding.local_variable_set(symbol, obj) → obj
proc.c
View on GitHub ↗
static VALUE
bind_local_variable_set(VALUE bindval, VALUE sym, VALUE val)
{
ID lid = check_local_id(bindval, &sym);
rb_binding_t *bind;
const VALUE *ptr;
const rb_env_t *env;
if (!lid) lid = rb_intern_str(sym);
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));
if ((ptr = get_local_variable_ptr(&env, lid, TRUE)) == NULL) {
/* not found. create new env */
ptr = rb_binding_add_dynavars(bindval, bind, 1, &lid);
env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
}
#if YJIT_STATS
rb_yjit_collect_binding_set();
#endif
RB_OBJ_WRITE(env, ptr, val);
return val;
}
Set local variable named symbol as obj.
Example
def foo a = 1 bind = binding bind.local_variable_set(:a, 2) # set existing local variable `a' bind.local_variable_set(:b, 3) # create new local variable `b' # `b' exists only in binding p bind.local_variable_get(:a) #=> 2 p bind.local_variable_get(:b) #=> 3 p a #=> 2 p b #=> NameError end
This method behaves similarly to the following code:
Example
binding.eval("#{symbol} = #{obj}")
if obj can be dumped in Ruby code.
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
#local_variables
#receiver
#local_variable_get
#source_location
also in
4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0