Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Kernel#binding

binding → a_binding

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

  1. 3.2
See also #BigDecimal #block_given? #autoload? #callcc also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0