MC logo
CSc 404 Assignment 3
[^] CSc 404 Home
[CSc 404 Assignment 1] [CSc 404 Assignment 2] [CSc 404 Assignment 3] [CSc 404 Assignment 4] [CSc 404 Assignment 5] [CSc 404 Assignment 6]

That's Not Nice

Feb 21
Mar 2
40 pts
Modify Ruby's built-in array class to contain method mean which returns the mean (sum divided by count). If the array is empty, it should return nil. If the array contains data for which the needed computations are not allowed, your method would be expected to crash. The numeric result should be floating point, even if the members are integers. Place your code a file with an .rb extension so it can be brought in with load.
[bennet@m-mcc-csc-01456 ruby]$ irb
irb(main):001:0> load "mean.rb"
=> true
irb(main):002:0> [4,9,12].mean
=> 8.333333333333334
irb(main):003:0> [3.4,11.2,18.4,2].mean
=> 8.75
irb(main):004:0> [15].mean
=> 15.0
irb(main):005:0> [].mean
=> nil
irb(main):006:0> ["fred","barney","sally"].mean
NoMethodError: undefined method `/' for "fredbarneysally":String
        from /home/bennet/courses/cs404/asst/ruby/mean.rb:4:in `mean'
        from (irb):6
        from /usr/bin/irb:12:in `<main>'
To do this, reopen the Array class and add the the method. Your method body can use all the existing methods of the array class. To call a method on yourself, use the object name self, which is similar to the this in Java and C++. For instance, you can subscript yourself with self[i]. Create a loop to add up all of your contents and return the result.


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