Guest User

Untitled

a guest
Feb 19th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. # [See the specs at the bottom for a more verbose description of these requirements]
  2. # A) Indent every line except the first (assume something as wide as INDENT
  3. # has already been printed) to INDENT spaces in.
  4. # B) Visible characters (non-whitespace) must never exceed WIDTH
  5. # 1) Wrap automatically at word boundary, if there is a boundary within
  6. # MIN_WIDTH
  7. # 2) Wrap automatically at WIDTH, if there is no boundary within MIN_WIDTH
  8. # C) Preserve existing whitespace (but do not include whitespace at EOL for B)
  9.  
  10. require 'rubygems'
  11. require 'spec'
  12.  
  13. class String
  14. def indent spaces
  15. if spaces.respond_to? :to_s # duck,
  16. self.split("\n").map {|s| [spaces, s].join }.join("\n")
  17. elsif spaces.respond_to? :to_i # duck,
  18. self.split("\n").map {|s| [(' ' * spaces), s].join }.join("\n")
  19. else # goose!
  20. raise ArgumentError, "#{spaces} is neither string-ish nor numeric-ish"
  21. end
  22. end
  23.  
  24. def wrap width
  25. raise ArgumentError, "#{width} is not numeric-ish" unless width.respond_to? :to_i
  26. # .{1,#{width}} # Any ammount of anything less than +width+ characters...
  27. # \b # ... that ends at a word boundary,
  28. # [^\w]? # ... including any punctuation, even over +width+ chars,
  29. # \s* # ... don't worry about whitespace after +width+
  30. self.scan(/.{1,#{width}}(\b[^\w]?)\s*/).join("\n")
  31. end
  32. end
  33.  
  34. describe String do
  35. describe '#indent' do
  36. it "should indent a single-line string" do
  37. string = 'abcdef'
  38. indented = string.indent(' ')
  39. indented.should == ' abcdef'
  40. end
  41.  
  42. it "should indent a multi-line string" do
  43. string = "abcdef\nghijkl"
  44. indented = string.indent(' ')
  45. indented.should == " abcdef\n ghijkl"
  46. end
  47.  
  48. it "should preserve whitespace" do
  49. string = "begin\n puts 'whee!'\nend"
  50. indented = string.indent(' ')
  51. indented.should == " begin\n puts 'whee!'\n end"
  52. end
  53. end
  54.  
  55. describe '#wrap' do
  56. it "should wrap a long, continuous string at `width`" do
  57. string = '0123456789' * 3
  58. wrapped = string.wrap(10)
  59. wrapped.should == "0123456789\n0123456789\n0123456789"
  60. end
  61.  
  62. it "should wrap a sentence at the last word boundary before `width`" do
  63. string = 'The quick blue merle Tucker jumped over the mean black and white Jazz.'
  64. wrapped = string.wrap(30)
  65. wrapped.should == "The quick blue merle Tucker \njumped over the mean black and \nwhite Jazz."
  66. end
  67. end
  68. end
Add Comment
Please, Sign In to add comment