hack to work around eval scoping?

S

Stephen Waits

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>" +
"<div class=\"output\">" +
h(output(code)) +
"</div>" +
"</div>"
end
%>

<html>
<head>
</head>
<body>

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

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

</body>
</html>


Thanks,
Steve
 
R

Robert Klemme

Stephen said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,042
Latest member
icassiem

Latest Threads

Top