2

I'm trying to write a debugger in ruby. I want to run some code every time a variable changes. I don't know the variables in advance.

At the moment I'm trying set_trace_func but it seems to execute before each line, rather than after each line eg;

set_trace_func proc { |event, file, line, id, binding, classname|
    if file == "(eval)"
        printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
        args = binding.eval("local_variables").inject({}) do |vars, name|
            value = binding.eval name.to_s
            vars[name] = value unless vars.nil?

            vars
        end
        puts args.inspect
    end
}

eval("blah = 4\nrar = 3\n")

set_trace_func(nil)

When I execute it I get;

n@VirtualBox:~$ ruby blah.rb 
    line (eval):1                     
{:blah=>nil, :rar=>nil}
    line (eval):2                     
{:blah=>4, :rar=>nil}
n@VirtualBox:~$

This is not what I want - it's not showing the assignment to rar. Is there a better way to do this? As a hack, I added one last statement to the eval eg.

eval("blah = 4\nrar = 3\nnil\n")

but that doesn't fix the problem when it comes to loops etc.

I would like to get an output of what line a variable changed on and what it changed to in order.

1 Answer 1

1

I don't know of a mechanism in pure ruby to help you with writing a debugger and hooking low level execution features such as variable assignment. The ruby-debug is a C extension with deep knowledge and hooks in to the execution engine. You can read it here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response. My c knowledge is a bit out of date and I'm having a lot of trouble getting something useful from that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.