CSc 404 Assignment 4
Run Away! Run Away!
Add a method each_run to the Ruby Array class which takes a
code block expecting two arguments. It calls the code block once for
each contiguous run of equal items in the array, sending the length
of the run and the item repeated. (Of course, an item which is
not repeated constitutes a run of length 1, with the single item
“repeated” once.)
Place your code in a file which can be loaded or required.
To wit:
[bennet@m-mcc-csc-01456 asst]$ irb
irb(main):001:0> load("eachrun.rb")
=> true
irb(main):002:0> [5,9,3,4,4,4,7,8,8].each_run { |n,x|
irb(main):003:1* print x, " appearing ", n, " times\n" }
5 appearing 1 times
9 appearing 1 times
3 appearing 1 times
4 appearing 3 times
7 appearing 1 times
8 appearing 2 times
=> nil
irb(main):004:0> [3,3,3,3,7].each_run { |ct,v| print v,"[",ct,"]\n" }
3[4]
7[1]
=> nil
irb(main):005:0> ["sam","mike","mike","mike",3,9,9,"joe"].each_run { |n,x|
irb(main):006:1* print n," of ",x,"\n" }
1 of sam
3 of mike
1 of 3
2 of 9
1 of joe
=> nil
irb(main):007:0> [5,6,7].each_run { |ct,v| print v,"[",ct,"]\n" }
5[1]
6[1]
7[1]
=> nil
irb(main):008:0> [4,4,4,7,7,2,4,4,6,6,6,6,7].each_run {
irb(main):008:1* |num,val| print val," * ",num,"\n" }
4 * 3
7 * 2
2 * 1
4 * 2
6 * 4
7 * 1
=> nil
Make sure that your method does not modify the array that it is called on.
Submission
When your function works, is nicely formatted and documents,
submit it using
this
form.