How to Get Ruby to Print a Full Backtrace Instead of a Truncated One

How do I get ruby to print a full backtrace instead of a truncated one?

Exception#backtrace has the entire stack in it:

def do_division_by_zero; 5 / 0; end
begin
do_division_by_zero
rescue => exception
puts exception.backtrace
raise # always reraise
end

(Inspired by Peter Cooper's Ruby Inside blog)

How can I force Ruby to show a full stack trace?


begin
# Code that raises exception
rescue StandardError => e
puts e.backtrace
end

Log exact exception origin and its backtrace at_exit in Ruby

Backtrace already contains file and lineno, $@ global contains a backtrace.

How do I get this block of ruby to add each individual hash into an array instead of just adding one hash multiple times?

Create sessions inside of the each_with_index block instead of outside:

sessions_array = []

@session.each do |element|
sessions = {
time: element[0],
action: element[1],
user: element[2],
}
sessions_array << sessions
end

puts sessions_array

However, this can be done much more succinctly. When you're turning an array into another array with the same number of elements you almost always want to use map. Also, in a Ruby block you can extract the elements from an array by specifying multiple names in its arguments (|foo, bar, ...|).

This code is equivalent to the above:

sessions_array = @session.map do |time, action, user|
{ time: time, action: action, user: user }
end

You can see both of these snippets in action on repl.it here: https://repl.it/@jrunning/NavyImmaculateShockwave



Related Topics



Leave a reply



Submit