RubyTree
RubyTree copied to clipboard
Allow input of a custom IO for print_tree
The default is for print_tree to send output to stdout, I would like the option to send it somewhere else by passing in and IO object to it.
Currently, I'm using this workaround, but I don't really like capturing all of stdout (even if temporarily):
def fetch_tree_text(tree)
begin
old_stdout = $stdout
$stdout = StringIO.new
tree.print_tree
$stdout.string
ensure
$stdout = old_stdout
end
end
I would much rather do something like this:
def fetch_tree_text(tree)
string_io = StringIO.new
tree.print_tree(io: string_io)
string_io.string
end
Or maybe even better, have a method that does the same thing, but returns a string, instead sending to an IO.
Hello! print_tree accept a lambda. The default one emit a puts. but you can pass your code.
for example:
def work_on_row(node, prefix)
# same as default result but on @io
@io.puts "#{prefix} #{node.name}"
end
@io = StringIO.new
tree.print_tree(,, method(:work_on_row))
#do someting with @io.
Hope this help