Output lines to stdout for debug

A

Andrew Walrond

Is there an easy way of getting each line of a ruby script to be written to
stdout before being executed?
I currently use a wrapper function which takes the command as a string and
puts()'s then eval()'s it, but thats very ugly.

Any suggestions?

Andrew Walrond
 
M

mark

Is there an easy way of getting each line of a ruby script to be written to
stdout before being executed?
I currently use a wrapper function which takes the command as a string and
puts()'s then eval()'s it, but thats very ugly.

Any suggestions?

The following function will do the trick

def trace_program(file)
lines = File.readlines(file)
set_trace_func proc do |event, file, line, *extra|
puts lines[line - 1] if event == "line"
end
end

This reads the file into an array then sets up a system hook to get the line
number of each line before it's executed, and prints the line from the array.

Then you do something like

trace_program(__FILE__)

puts "x"
puts "y"
puts "z"

which outputs
puts "x"
x
puts "y"
y
puts "z"
z

Though there is probably a more Rubyist way to do this.
Andrew Walrond

Best Regards

Mark Sparshatt
 
N

nobu.nokada

Hi,

At Wed, 3 Sep 2003 19:06:05 +0900,
Andrew said:
Is there an easy way of getting each line of a ruby script to be written to
stdout before being executed?
I currently use a wrapper function which takes the command as a string and
puts()'s then eval()'s it, but thats very ugly.

tracer.rb
 
A

Andrew Walrond

Thanks - perfect!

----- Original Message -----
From: "mark" <[email protected]>
To: "ruby-talk ML" <[email protected]>
Sent: Wednesday, September 03, 2003 2:11 PM
Subject: Re: Output lines to stdout for debug

Is there an easy way of getting each line of a ruby script to be written to
stdout before being executed?
I currently use a wrapper function which takes the command as a string and
puts()'s then eval()'s it, but thats very ugly.

Any suggestions?

The following function will do the trick

def trace_program(file)
lines = File.readlines(file)
set_trace_func proc do |event, file, line, *extra|
puts lines[line - 1] if event == "line"
end
end

This reads the file into an array then sets up a system hook to get the line
number of each line before it's executed, and prints the line from the array.

Then you do something like

trace_program(__FILE__)

puts "x"
puts "y"
puts "z"

which outputs
puts "x"
x
puts "y"
y
puts "z"
z

Though there is probably a more Rubyist way to do this.
Andrew Walrond

Best Regards

Mark Sparshatt
 

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
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top