value of block parameter before evaluation

T

tjmkiely

I have a basic question about expressions as parameters to blocks.

If I pass and expression as the parameter to a block, is it possible to
get the string representation of the expression before evaluation.

For example, with the following block:

write = proc { |x| file.write("x:#{x})")}

If called like this:

write[request.domain]

I would like to have this printed:

request.domain: localhost

Thanks.
 
R

Robert Klemme

I have a basic question about expressions as parameters to blocks.

If I pass and expression as the parameter to a block, is it possible to
get the string representation of the expression before evaluation.

For example, with the following block:

write = proc { |x| file.write("x:#{x})")}

If called like this:

write[request.domain]

I would like to have this printed:

request.domain: localhost

What you want is not possible with normal means. The simplest solution
would be to hand over the expression as string but then you also need to
provide the binding. Something along the lines

write = lambda {|expr, bind| file.write "#{expr}:#{eval(expr,bind)}" }

More complex solutions involve parsing the source code.

Cheers

robert
 
D

Daniel Schierbeck

write = proc { |x| file.write("x:#{x})")}

If called like this:

write[request.domain]

I would like to have this printed:

request.domain: localhost

I'm not sure, but maybe something along the lines of this?

write = proc{|x| file.write("#{x}: #{eval(x)}")}
write.call("request.domain")


Daniel
 
T

Timothy Goddard

This isn't possible as there is no 'string representation' that the
Ruby interpreter is aware of. It could be any expression, and the text
wouldn't exist at all at runtime. The easiest way to do something like
this is to pass in a hash and repeat a block for each name, value pair.
 

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

No members online now.

Forum statistics

Threads
474,206
Messages
2,571,069
Members
47,677
Latest member
MoisesKoeh

Latest Threads

Top