CSc 404 Assignment 3

String Over Integer

Assigned
Due

Feb 16
45 pts
Feb 29

Create a Ruby definition which adds the division operator to the standard string class. When dividing a string by an integer, the operator produces an array of strings. The size of the array is the given integer, and contents of the array are parts of the string that, when concatenated in order, produce the original string. The parts are as equal in size as possible. If the string length is not exactly divisible by the dividing integer, some strings will be (one character) longer than some others. No two strings differ in length by more than one, and any longer ones appear before any shorter ones. For instance:

irb(main):001:0> load 'strdiv.rb' => true irb(main):002:0> "Something" / 3 => ["Som", "eth", "ing"] irb(main):003:0> "Something else" / 3 => ["Somet", "hing ", "else"] irb(main):004:0> "This is a relatively long string" / 7 => ["This ", "is a ", "relat", "ively", " lon", "g st", "ring"] irb(main):005:0> "booooooooooooooooooooo" / 5 => ["boooo", "ooooo", "oooo", "oooo", "oooo"] irb(main):006:0> "booooooooooooooooooooo" / 4 => ["booooo", "oooooo", "ooooo", "ooooo"] irb(main):007:0> "booooooooooooooooooooo" / 3 => ["booooooo", "ooooooo", "ooooooo"] irb(main):008:0> "booooooooooooooooooooo" / 2 => ["boooooooooo", "ooooooooooo"] irb(main):009:0> "booooooooooooooooooooo" / 1 => ["booooooooooooooooooooo"] irb(main):010:0> "booooooooooooooooooooo" / 11 => ["bo", "oo", "oo", "oo", "oo", "oo", "oo", "oo", "oo", "oo", "oo"]

Dividing a string by a negative or zero number, or dividing by a value which is not an integer is undefined. Your operator is welcome to break in any way you like.

Your code must reopen the string class and add a definition of the method /. Ruby already allows the method / to be called as an operator, so you don't need to do anything special to make that happen. Just define a method named /. You should be able to use the load command to read your file into ruby as shown above (though you may use any file name you like). In your method, use the keyword self to refer to the string you are (just as this is used in Java).

There are many ways to solve this. I simply made an empty array, then entered a loop which created each string and added to the array with the push method. That's a method of arrays which adds an item to the end of the array. Alternatively, you may grow a Ruby array using the + operator for concatenation.

When your function works, is nicely formatted and documents, submit it using this form.