Thursday, June 10, 2010

Ruby. Array.size by conditions

class Array
    def size(&closure)
        closure ? inject(0){ |count, elem| (yield elem) ? count + 1 : count } : length
    end
end

array = [1, 2, 3, 4, 5, 6]
puts array.size{ |i| (i & 1).zero? }.inspect

No comments: