Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Kernel#binding
() -> ::Binding
binding → a_binding
proc.c
View on GitHub ↗
static VALUE
rb_f_binding(VALUE self)
{
return rb_binding_new();
}
Returns a Binding object, describing the variable and method bindings at the point of call. This object can be used when calling Binding#eval to execute the evaluated command in this environment, or extracting its local variables.
Example
class User def initialize(name, position) @name = name @position = position end def get_binding binding end end user = User.new('Joan', 'manager') template = '{name: @name, position: @position}' # evaluate template in context of the object eval(template, user.get_binding) #=> {name: "Joan", position: "manager"}
Binding#local_variable_get can be used to access the variables whose names are reserved Ruby keywords:
Example
# This is valid parameter declaration, but `if` parameter can't # be accessed by name, because it is a reserved word. def validate(field, validation, if: nil) condition = binding.local_variable_get('if') return unless condition # ...Some implementation ... end validate(:name, :empty?, if: false) # skips validation validate(:name, :empty?, if: true) # performs validation
Ruby version changes
-
3.2
-
Kernel#bindingraisesRuntimeErrorif called from a non-Ruby frame (such as a method defined in C). [Bug #18487]
-
See also
#autoload_relative
#block_given?
#autoload?
#callcc
also in
4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0