Afficher un message
Vieux 16/09/2007, 00h43   #4
Patrick Hurley
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: one line to print the statement AS WELL AS the evaluated value like in C

On 9/15/07, Summercool <Summercoolness@gmail.com> wrote:
> It works! both for globals and for instance variables...
> but what is this call dbg{"n"} using { } instead of ( )
> does it have a name? and does any book talk about it?
>
> i guess there is no way to do


Using other people's magic try this:

require 'rubygems'
require 'ruby2ruby'

def annotated(&blk)
# the real magic, thanks ZenSpider :-)
lines = blk.to_ruby

# Turn the results into an array
lines = lines.split(/\n/)

# Chop off the proc stuff
lines = lines[1..-2]

# Find longest expression in block
max_width = lines.map { |l| l.size }.max

# scope result, so we can be polite and return it
result = nil

# Process each line, why limit ourselves to one
lines.each do |line|
# get the result, be sure to keep the correct binding
result = eval(line, blk.binding)

# format and display the output line
puts "#{line} #{" " * (max_width - line.size)}=> #{result.inspect}"
end

result
end

array = [1, 2, 3, 4]
annotated do
array.map { |v| v * 2 }
array[3] + 1
end

### Needs better exception handling to be "real"
### pth

  Réponse avec citation
 
Page generated in 0,08067 seconds with 9 queries