TonyTroev

RubyBoxClassExp

Feb 2nd, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.17 KB | None | 0 0
  1. # Box drawing class.
  2. class Box
  3.   # Initialize to given size, and filled with spaces.
  4.   def initialize(w,h)
  5.     @wid = w
  6.     @hgt = h
  7.     @fill = ' '
  8.   end
  9.  
  10.   # Change the fill.
  11.   def fill(f)
  12.     @fill = f
  13.     return self
  14.   end
  15.  
  16.   # Rotate 90 degrees.
  17.   def flip
  18.     @wid, @hgt = @hgt, @wid
  19.     return self
  20.   end
  21.  
  22.   # Generate (print) the box
  23.   def gen
  24.     line('+', @wid - 2, '-')
  25.     (@hgt - 2).times { line('|', @wid - 2, @fill) }
  26.     line('+', @wid - 2, '-')
  27.   end
  28.  
  29.   # For printing
  30.   def to_s
  31.     fill = @fill
  32.     if fill == ' '
  33.       fill = '(spaces)'
  34.     end
  35.     return "Box " + @wid.to_s + "x" + @hgt.to_s + ", filled: " + fill
  36.   end
  37.  
  38. private
  39.   # Print one line of the box.
  40.   def line(ends, count, fill)
  41.     print ends;
  42.     count.times { print fill }
  43.     print ends, "\n";
  44.   end
  45. end
  46.  
  47. # Create some boxes.
  48. b1 = Box.new(10, 4)
  49. b2 = Box.new(5,12).fill('$')
  50. b3 = Box.new(3,3).fill('@')
  51.  
  52. print "b1 = ", b1, "\nb2 = ", b2, "\nb3 = ", b3, "\n\n"
  53.  
  54. # Print some boxes.
  55. print "b1:\n";
  56. b1.gen
  57.  
  58. print "\nb2:\n";
  59. b2.gen
  60.  
  61. print "\nb3:\n";
  62. b3.gen
  63.  
  64. print "\nb2 flipped and filled with #:\n";
  65. b2.fill('#').flip.gen
  66. print "\nb2 = ", b2, "\n"
Add Comment
Please, Sign In to add comment