Capturing warning messages
问题 Is there a way to capture the warnings, something like rescue for exceptions? I do not want to simply disable the warnings (by doing $VERBOSE = nil ) but want to capture the content of the warning messages during run time. 回答1: You can redirect stderr to a StringIO object to capture the warnings output in a string: require 'stringio' old_stderr = $stderr $stderr = StringIO.new Foo = 1 Foo = 2 # generates a warning puts $stderr.string # prints the warning $stderr = old_stderr 回答2: require