Skip over iteration in Enumerable#collect

后端 未结 6 1396
春和景丽
春和景丽 2020-12-12 21:32
(1..4).collect do |x|
  next if x == 3
  x + 1
end # => [2, 3, nil, 5]
    # desired => [2, 3, 5]

If the condition for next is m

6条回答
  •  猫巷女王i
    2020-12-12 21:44

    You could pull the decision-making into a helper method, and use it via Enumerable#reduce:

    def potentially_keep(list, i)
      if i === 3
        list
      else
        list.push i
      end
    end
    # => :potentially_keep
    
    (1..4).reduce([]) { |memo, i| potentially_keep(memo, i) }
    # => [1, 2, 4]
    

提交回复
热议问题