# Hack to work around eval scoping?

**URL:** <https://www.ruby-forum.com/t/hack-to-work-around-eval-scoping/77706>\
**Category:** Ruby\
**Created:** [March 7, 2006, 10:17am UTC](https://www.ruby-forum.com/t/hack-to-work-around-eval-scoping/77706 "2006-03-07T10:17:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sgware](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/48db29/32.png) [@sgware](https://www.ruby-forum.com/u/sgware)\
**Post date:** [March 7, 2006, 10:17am UTC](https://www.ruby-forum.com/t/hack-to-work-around-eval-scoping/77706/1 "2006-03-07T10:17:58Z")

</div>

I’ve learned that in 1.8 eval is scoped like a block… I’m wondering how  
I might get around that?

For a little background, here’s what I’m working on. Essentially an erb  
script of Ruby examples, that lists code and output neatly. It’s  
basically similar to a non-interactive version of why’s try ruby - well,  
in some ways. I think… 🙂

Anyway, here’s the shell of the script which demonstrates my problem, in  
case I haven’t explained myself clearly enough:

\<%  
require ‘syntax/convertors/html’  
include ERB::Util

def output(code)  
result = eval(code)  
if result  
result.to\_s  
else  
“nil”  
end  
end

# would be nice to pass this an array

# of strings to be eval’d in sequence too

def ruby(code)  
convertor = Syntax::Convertors::HTML.for\_syntax “ruby”  
“\<div class=“examplelist”\>” +  
“\<div class=“example”\>” +  
“\<div class=“code”\>” +  
convertor.convert( code.gsub(/\t/," ") ) +  
“” +  
“\<div class=“output”\>” +  
h(output(code)) +  
“” +  
“”  
end  
%\>

\<%= ruby( \<\<EOS  
a = 1 + 2  
EOS  
) %\>

\<%= ruby( \<\<EOS  
a # undefined because in 1.8 eval is scoped like blocks  
EOS  
) %\>

Thanks,  
Steve

---

<div class="post-metadata">

**Author:** ![sgware](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/48db29/32.png) [@sgware](https://www.ruby-forum.com/u/sgware)\
**Post date:** [March 7, 2006, 10:36am UTC](https://www.ruby-forum.com/t/hack-to-work-around-eval-scoping/77706/2 "2006-03-07T10:36:07Z")

</div>

Stephen W. wrote:

> I’ve learned that in 1.8 eval is scoped like a block… I’m wondering  
> how I might get around that?

You can use eval with a binding argument:

10:21:12 [c]: ruby -e ‘def f() x=1; g(“x=6”, binding); puts x; end; def  
g(c,b) eval(c,b) end; f’  
6

Kind regards

```
robert
```
