Today I Learned

hashrocket A Hashrocket project

Ruby Binding Class

Ruby’s Binding class allows you to access classes, variables, and methods outside of the current scope.

class Foo
	def bar
		my_var = 20
		binding()
	end
end

Normally, if you made reference to my_var outside of that method, you’d get an error. Binding objects allow you to do this:

my_foo = Foo.new

foo_bar = my_foo.bar
puts foo_bar.eval('my_var')

# 20
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.