Connect With Us

What is `binding` object in Ruby?

By Shiva Bhusal on Jun, 03, 2016

 

Lets see an example before we explain the term binding

def binding1
  occupation = 'chor'
  binding
end

def binding2
  occupation = 'engineer'
  binding
end

erb = "Ram prasad is <%= occupation %>"
ERB.new(erb).result(binding1)
# => "Ram prasad is chor"
ERB.new(erb).result(binding2)
# => "Ram prasad is engineer"

Looking into the example, some of you might have gotten the idea that binding is nothing more than an object representing a closure where variables/objects are defined. Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. You can also imagine this as a variable representing container where stuffs are defined.

For more info see this

Example:

class Demo
  def initialize(n)
    @secret = n
  end
  def get_binding
    return 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

Share This:

Latest Posts


Integrating Afterpay Payment in a Rails Project By Umesh P Kafle on Sep, 07, 2018

Switching to React Native from Ruby on Rails By Kamal Pandey on Aug, 29, 2018

Jyaasa in IT Career Fair 2018 By Sonika Thapa on Jun, 12, 2018

Encrypted secrets in Ruby on Rails By Rasna Shakya on Apr, 20, 2018

Rails Payment Integration with zipPay (Buy Now and Pay Later) By Nelson Suwal on Mar, 23, 2018