Binding 클래스

Binding 클래스

Binding 클래스의 객체는 코드의 특정 지점에서의 실행 컨텍스트를 담아 두고, 그 컨텍스트를 나중에 쓸 수 있게 보관해요. 그 지점에서 접근할 수 있는 변수, 메서드, self의 값, 그리고 가능하면 이터레이터 블록까지 모두 보존돼요. Binding 객체는 Kernel#binding으로 만들 수 있고, Kernel#set_trace_func의 콜백과 TracePoint 인스턴스에도 전달돼요.

출처: Ruby 4.0 API

본문

Binding 객체는 특정 지점에서의 실행 컨텍스트를 캡슐화해요. 변수, 메서드, self의 값, 가능하면 이터레이터 블록까지 보존돼요. Kernel#binding으로 만들 수 있고 Kernel#set_trace_func 콜백과 TracePoint 인스턴스에 제공돼요.

이 binding 객체는 Kernel#eval 메서드의 두 번째 인자로 전달되어 평가 환경을 설정할 수 있어요.

class Demo
  def initialize(n)
    @secret = n
  end
  def get_binding
    binding
  end
end

k1 = Demo.new(99)
b1 = k1.get_binding
k2 = Demo.new(-3)
b2 = k2.get_binding

eval("@secret", b1)   #=> 99
eval("@secret", b2)   #=> -3
eval("@secret")       #=> nil

Binding 객체에는 클래스 고유의 메서드가 따로 없어요. (즉 이 페이지의 메서드들은 전부 Kernel#eval 등에서 쓰기 위한 것들이에요.)

Public Instance Methods

eval(string [, filename [,lineno]]) → obj

string에 담긴 Ruby 표현식을 binding의 컨텍스트에서 평가해요. 선택적 filenamelineno 인자가 있으면 문법 오류를 보고할 때 사용돼요.

def get_binding(param)
  binding
end
b = get_binding("hello")
b.eval("param")   #=> "hello"

implicit_parameter_defined?(symbol) → obj

번호 붙은 매개변수(numbered parameter) 또는 "it" 매개변수가 존재하면 true를 돌려줘요.

def foo
  [42].each do
    it
    binding.implicit_parameter_defined?(:it) #=> true
    binding.implicit_parameter_defined?(:_1) #=> false
  end

  { k: 42 }.each do
    _2
    binding.implicit_parameter_defined?(:_1) #=> true
    binding.implicit_parameter_defined?(:_2) #=> true
    binding.implicit_parameter_defined?(:_3) #=> false
    binding.implicit_parameter_defined?(:it) #=> false
  end
end

implicit_parameter_get(symbol) → obj

번호 붙은 매개변수 또는 "it" 매개변수의 값을 돌려줘요.

def foo
  [42].each do
    it
    binding.implicit_parameter_get(:it) #=> 42
  end

  { k: 42 }.each do
    _2
    binding.implicit_parameter_get(:_1) #=> :k
    binding.implicit_parameter_get(:_2) #=> 42
  end
end

implicit_parameters → Array

binding에서 정의된 번호 붙은 매개변수와 "it" 매개변수의 이름을 돌려줘요.

def foo
  [42].each do
    it
    binding.implicit_parameters #=> [:it]
  end

  { k: 42 }.each do
    _2
    binding.implicit_parameters #=> [:_1, :_2]
  end
end

local_variable_defined?(symbol) → obj

지역 변수 symbol이 존재하면 true를 돌려줘요.

def foo
  a = 1
  binding.local_variable_defined?(:a) #=> true
  binding.local_variable_defined?(:b) #=> false
end

이 메서드는 다음 코드의 짧은 버전이에요:

binding.eval("defined?(#{symbol}) == 'local-variable'")

local_variable_get(symbol) → obj

지역 변수 symbol의 값을 돌려줘요.

def foo
  a = 1
  binding.local_variable_get(:a) #=> 1
  binding.local_variable_get(:b) #=> NameError
end

이 메서드는 다음 코드의 짧은 버전이에요:

binding.eval("#{symbol}")

local_variable_set(symbol, obj) → obj

symbol 이름의 지역 변수를 obj로 설정해요.

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

obj가 Ruby 코드로 덤프될 수 있다면, 이 메서드는 다음 코드와 비슷하게 동작해요:

binding.eval("#{symbol} = #{obj}")

local_variables → Array

binding의 지역 변수 이름을 심볼로 돌려줘요.

def foo
  a = 1
  2.times do |n|
    binding.local_variables #=> [:a, :n]
  end
end

이 메서드는 다음 코드의 짧은 버전이에요:

binding.eval("local_variables")

receiver → object

binding 객체에 묶인 수신자(receiver)를 돌려줘요.

source_location → [String, Integer]

binding 객체의 Ruby 소스 파일명과 줄 번호를 돌려줘요.