# Ruby bindings

**URL:** <https://www.ruby-forum.com/t/ruby-bindings/104073>\
**Category:** Ruby\
**Created:** [May 14, 2007, 2:15am UTC](https://www.ruby-forum.com/t/ruby-bindings/104073 "2007-05-14T02:15:29Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![samaaron](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/da6949/32.png) [@samaaron](https://www.ruby-forum.com/u/samaaron)\
**Post date:** [May 14, 2007, 2:15am UTC](https://www.ruby-forum.com/t/ruby-bindings/104073/1 "2007-05-14T02:15:29Z")

</div>

Hi there,

I was wondering whether it would be possible for someone to spend a  
moment  
of their time to either answer my question, or point me in the right  
direction regarding some interesting (to me) Ruby behaviour w.r.t.  
Kernel#binding, Kernel#eval and ERB#result.

Here’s an example class I knocked up to illustrate my findings:

class Cheese  
def please\_dont\_burn\_me!  
#doesn’t work  
eval “stilton = ‘tasty’”  
puts "Stilton is " + stilton  
end

def just\_melted\_is\_best  
#does work  
eval “shropshire\_blue = ‘very tasty’”  
eval “puts 'Shropshire Blue is ’ + shropshire\_blue”  
end

def throw\_cubes\_in\_the\_air\_and\_catch\_them\_in\_your\_mouth  
#again, doesn’t work  
eval “cheddar = ‘the staple cheese’”  
puts ERB.new(“Cheddar is \<%= cheddar %\>”).result  
end

def grated\_is\_good  
#passing it the current binding allows it to work  
eval “brie = ‘best consumed when warm and runny’”  
puts ERB.new(“Brie is \<%= brie %\>”).result(binding)  
end  
end

I understand why Cheese#please\_dont\_burn\_me! doesn’t work; apparently  
around Ruby 1.8 any assignments made within an eval aren’t available  
to the general context (following block-like semantics). However, this  
doesn’t seem to explain why Cheese#just\_melted\_is\_best works. There is  
similar behaviour with ERB#result; by explicitly passing the current  
binding, the result method is able to see the variable cheddar.  
Interestingly, when these examples are declared outside of an explicit  
class declaration, we see slightly different behaviour:

#still doesn’t work (as expected)  
eval “stilton = ‘tasty’”  
puts "Stilton is " + stilton

#works  
eval “shropshire\_blue = ‘very tasty’”  
eval “puts 'Shropshire Blue is ’ + shropshire\_blue”

#this time it works…  
eval “cheddar = ‘the staple cheese’”  
puts ERB.new(“Cheddar is \<%= cheddar %\>”).result

#works  
eval “brie = ‘best consumed when warm and runny’”  
puts ERB.new(“Brie is \<%= brie %\>”).result(binding)

I guess my question is: is there an easy way of explaining and  
understanding how bindings operate in these situations, or is the  
answer just due to the quirks of the c implementation?

Yours,

Sam A.

* * *

> **[Sam Aaron - A Communicative Programmer](http://sam.aaron.name)**
>
> Dr. Sam Aaron is a software architect and computational thinker with a deep fascination with the notion of communicative programming.
