Skip over iteration in Enumerable#collect

后端 未结 6 1397
春和景丽
春和景丽 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条回答
  •  难免孤独
    2020-12-12 21:36

    just a suggestion, why don't you do it this way:

    result = []
    (1..4).each do |x|
      next if x == 3
      result << x
    end
    result # => [1, 2, 4]
    

    in that way you saved another iteration to remove nil elements from the array. hope it helps =)

提交回复
热议问题