Hack to work around eval scoping?


#1

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… :slight_smile:

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


#2

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