How to add an if method to an array

I have an array of numbers like this ...

a= [28, 67, 20, 38, 4, 39, 14, 84, 20, 64, 7, 24, 17, 8, 7, 6, 15, 52, 4, 26]

I need to check if each of the numbers has more than 30, and if so, I want to count this number and count the number of numbers more than 30. I have this, but it does not work yet

def late_items
    total_late = []
     if a.map { |i| i > 30}
      total_late << i
     end
    self.late_items = total_late.count
end
+4
source share
5 answers

The method countcan be passed in block to indicate which elements should be considered. Elements for which the block returns falseor nilare ignored.

In your case, it comes down to the following:

array.count { |element| element > 30 }
+5
source

You can use selectmore than 30 to get all the items.

a.select{|b| b > 30}.count
# => 6 
+2
source

Ruby :

a = [28, 67, 20, 38, 4, 39, 14, 84, 20, 64, 7, 24, 17, 8, 7, 6, 15, 52, 4, 26]

a.select{ |e| e > 30 }
0

, , 30, , :

a= [28, 67, 20, 38, 4, 39, 14, 84, 20, 64, 7, 24, 17, 8, 7, 6, 15, 52, 4, 26]
count = 0
pos = []
a.each_with_index do |num, i|
    if num > 30
        count += 1
        pos << i
    end
end

puts count
print pos

#=> 6 [1,3,5,7,8,17]
0

inject. 30:

a.inject(0) { |sum, n| n > 30 ? sum += n : sum }

Or, if you have an array of numbers greater than 30, you can use reduceto summarize its elements. In your variable, ait will look like this:

a.select{ |n| n > 30 }.reduce(&:+)
-1
source

Source: https://habr.com/ru/post/1583804/


All Articles