This content originally appeared on DEV Community and was authored by Jesse vB
If you're a Ruby developer, you might have encountered something like the following:
binding.pry
binding.irb
binding.break
If your code runs one of these expressions, the execution will halt, and a REPL session will start from that context.
Have you ever wondered what a "binding" is exactly? Or how to use one? I'm hoping to answer both questions here, so let's go!
What is a binding?
A Ruby binding is...
An encapsulation of the execution context at some particular place in the code.
If you'd like to see exactly how Ruby creates the Binding class, you can find the source code here.
So, a binding encapsulates or "takes a snapshot" of a particular place in the code during execution. To illustrate this, imagine holding a photograph of an old-fashioned telephone.
Photo by Eckhard Hoehmann on Unsplash
This photograph was taken before smart phones were invented. What if you could jump back into 1984? You might ask people about smart phones, to which they would give you a blank stare.
Similarly, if you jumped into a photo taken in 2010 and asked about ChatGPT, you'd also receive "deer in headlights". In this sense, the photo is like the binding.
With bindings, we can jump back into the way things were.
Using bindings
Ruby makes this easy. Simply invoke the method binding
, available globally. It will return an instance of the class Binding
.
b = binding
b.class
=> Binding
The class itself has no variables, constants, or methods of its own, but the instances will encapsulate the context upon instantiation.
# Capture context #1
year_1984 = binding
i_phone = :invented
# Capture context #2
year_2010 = binding
chat_gpt = :invented
# Capture context #3
year_2025 = binding
In 1984, neither technologies were invented yet. In 2010 only the iPhone was invented, and in 2025, both have been invented.
We can see this clearly through the #eval
method which takes a String argument (something to evaluate) and an optional binding. If not specified, it defaults to the current context.
# evaluating from the first context...
eval("i_phone", year_1984) # => NameError
eval("chat_gpt", year_1984) # => NameError
# evaluating from the second context...
eval("i_phone", year_2010) # => :invented
eval("chat_gpt", year_2010) # => NameError
# evaluating from the third context...
eval("i_phone", year_2025) # => :invented
eval("chat_gpt", year_2025) # => :invented
This content originally appeared on DEV Community and was authored by Jesse vB

Jesse vB | Sciencx (2025-03-16T18:58:00+00:00) What exactly is a Ruby binding?. Retrieved from https://www.scien.cx/2025/03/16/what-exactly-is-a-ruby-binding/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.