如何使用if方法添加到数组

时间:2015-04-21 15:11:47

标签: ruby arrays methods

我有一系列数字,如此...

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

我需要检查每个数字是否大于30,如果是,那么我想计算这个数字,并计算出多少数字大于30的数量。我有这个但是到目前为止它没有工作< / p>

def late_items
    total_late = []
     if a.map { |i| i > 30}
      total_late << i
     end
    self.late_items = total_late.count
end

5 个答案:

答案 0 :(得分:5)

count方法可以传递一个块来指定应该计算哪种元素。块返回falsenil的元素将被忽略。

在你的情况下,它可以归结为:

array.count { |element| element > 30 }

答案 1 :(得分:2)

您可以使用select获取大于30的所有元素。

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

答案 2 :(得分:0)

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 }

答案 3 :(得分: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]

答案 4 :(得分:-1)

您也可以查看inject方法。在其中,您可以轻松获得大于30的数字之和:

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

或者,如果您有一个大于30的数字数组,则可以使用reduce汇总其项目。在a变量中,它将如下所示:

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