0
describe Array do
  describe "#sum" do
    it "has a #sum method" do
      expect([]).to respond_to(:sum)
    end

    it "should be 0 for an empty array" do
      expect([].sum).to eq(0)
    end

    it "should add all of the elements" do
      expect([1,2,4].sum).to eq(7)
    end
  end
end

the code above is the test code given to me. and I made the code below to be tested by the test code.

class Array

    def initialize(arr)
        @arr = arr    
    end

    def sum
        if @arr == nil
            return 0
        else
            numArr = @arr
            total = 0 
            numArr.each {|num|
                total += num
            }
            return total
        end
    end
end

I thought it would return total 7. (1+2+4 = 7) but it returns 0... I guess it doesn't take [1,2,4] array as a parameter. what am I doing wrong?

0

1 Answer 1

1

As the existing array class already has an initializer, and self inside the instance of an array already is an array, you don't need to add your own initializer

class Array

  def sum
    self.inject(0){|sum,x| sum + x }
  end

end

should do what you want. Lookup inject if it isn't clear, but it does essentially the same that you tried to do with your code, just that you were using a local variable to store the sum.

If this is not only an experiment however I recommend not do monkey patches on core classes if avoidable (and it usually is avoidable). Here's an article with some hints how to do it a bit cleaner, if not avoidable: http://www.justinweiss.com/articles/3-ways-to-monkey-patch-without-making-a-mess/

Sign up to request clarification or add additional context in comments.

2 Comments

I have one more question, if you don't mind. so you said it has already initialize in it, and what if I want to get only [1,2,4] the array itself? how can I access it? (in your answer above, how does 'x' get the array [1,2,4]?
In the example above 'self' is referencing the array. 'def sum' is an instance method, so self inside this method refers to the instance of the array - In this case [1, 2, 4] What inject does is basically defining sum = 0; then iterating through the array (x always being one element in the array).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.