简体   繁体   中英

Sum only integers in array (Ruby)

I'm attempting to sum only the integers in an array that is passed to my function but keep running up against errors. This is what I have right now.

def sum(*x)
    x.each { |i|
        unless i.is_a? Integer
            x.delete_at(x.index(i)) 
        end
    }
    x.inject(:+)
end

I don't know the numbers of items that might be in the array as you can see the splat operator. I then loop through each array item and check if it's an integer. If it isn't, it is deleted. Finally after only integers are left, the array is summed.

However, I keep getting the following error.

No implicit conversion of Fixnum into String (TypeError)

(This error references the line inject is on. Any idea what I'm doing wrong here?

There is a cute solution for this :-

your_array.grep(Integer).reduce(0, :+)

Thus, implement your method as :

def sum(*x)
  x.grep(Integer).reduce(0, :+)
end

Read #grep to understand how it works.

Returns an array of every element in enum for which Pattern === element. If the optional block is supplied, each matching element is passed to it, and the block's result is stored in the output array.

x.each iterates through each index of the array as it was at the time of method application. Suppose you had x = ["a", "b", "c"] . In the first iteration over x.each , i as in your code is "a" at index 0. Your code deletes this element from x , making it ["b", "c"] . The iteration goes to index 1 , and i is now "c" at index 1. Here, the iteration has skipped "b" . As a result, the x you intended to have checked includes elements that are not integers, and you get the error in doing inject(:+) .

Keep it simple! No need to modify your existing array, just select what you need!

irb(main):001:0> a=[1,2,"a",3]
=> [1, 2, "a", 3]

irb(main):002:0> a.select {|ax| ax.is_a? Integer}.reduce(0, :+)
=> 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM