Jeppe Jakobsen wrote:
Hi there, I have a question regarding how to implant a new method into
the
class Array. I would like to write a ruby file that sums all of the
digits
in an array. I have tried this:
class Array
def Array.sum
until (Array.empty?)
arraySum += Array.pop
end
puts arraySum
end
end
Gave no error when I ran the code. My problem occur when i try to use
this
method:
require "Library/Array_sum.rb"
a = [1..100]
a.sum
I get a NoMethodError on sum. Can anybody tell me what I did wrong here?
Thanks in advance
Jeppe,
You have a number of problems here. First, if what you are really trying
to do is to sum the array, rather than just learn how to add methods to
a class, then all you have to do is
a = [1,2,3]
a.inject { |v,n| v+n }
=> 6
Second, you created your function as a class method rather than an
instance method by calling it Array.sum. All you need is
def sum
...
end
This may be why you are getting the MethodNotFound, since the instance
of array "a" does not have this method - the class Array does.
Finally, a = [1..100] will give you an array with the first value being
the range [1..100], not an array with all the values from 1 to 100,
[1,2,3...].
Two suggestions: learn to use irb to see what happens when you call
methods, and (2) pick up Programming Ruby by Dave Thomas if you have not
already done so. It explains all of this in detail.
Hope this helps,
Keith
···
--
Posted via http://www.ruby-forum.com/\.