从数组中获取特定索引的橙色

时间:2015-05-24 04:11:00

标签: ruby

class OrangeTree
  def initialize(age = 0, height = 0)
    @age = age
    @height = height
    @count = []
  end

  def aging
    until @age > 10
      screening_array = Array.new
      i = @age + 3
      i.times do
        screening_array << Orange.new
      end
      @age += 1
    end
    screening_array.each_with_index do |orange, index|
      @count << orange if index.even?
    end
    p @count
  end
end

class Orange
  attr_accessor :diameter
  # Initializes a new Orange with diameter +diameter+
  def initialize(diameter = rand(4) + 1)
    @diameter = diameter
  end
end

tree = OrangeTree.new
tree.aging

我正在尝试使用索引为3及以上的橙色来填充@count ..我能得到的最接近的是获得带有偶数索引的橙色..我该如何修改它?

1 个答案:

答案 0 :(得分:0)

您可以内联您尝试进行的比较:

screening_array.each_with_index do |orange, index|
  @count << orange if index > 3
end