Forum: Ruby hack to work around eval scoping?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Stephen W. (Guest)
on 2006-03-07 11:17
(Received via mailing list)
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
Robert K. (Guest)
on 2006-03-07 11:36
(Received via mailing list)
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
This topic is locked and can not be replied to.