Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- def cout(*args)
- raise 'no args' if args.empty?
- format = args.shift
- out = ''
- until format.empty?
- if m = format.match(/%(.)/)
- out << m.pre_match
- case m[1]
- when '%'
- out << '%'
- when 'd'
- raise 'few args' if args.empty?
- out << args.shift.to_i.to_s
- else
- raise "illegal input: \"#{m[1]}\""
- end
- format = m.post_match
- else
- break
- end
- end
- raise 'unmatch %' if format.include? '%'
- raise "too many args: #{args}" unless args.empty?
- puts out << format
- end
- require 'test/unit'
- class TestCout < Test::Unit::TestCase
- def capture_cout(*args)
- if args.empty?
- capture_output do
- cout
- end
- else
- capture_output do
- cout *args
- end
- end
- end
- def test_cout
- assert_raise_message('unmatch %') { capture_cout '%' }
- assert_raise_message('too many args: [2]') { capture_cout 'abc%d', 1, 2 }
- assert_raise_message('few args') { capture_cout 'abc%d' }
- assert_raise_message('illegal input: "i"') { capture_cout '%d %i', 1, 2 }
- assert_raise_message('no args') { capture_cout }
- assert_equal ["1 etc.\n", ''], capture_cout('%d etc.', 1)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement