How to map and remove nil values in Ruby

前端 未结 8 1600
野性不改
野性不改 2020-12-07 07:51

I have a map which either changes a value or sets it to nil. I then want to remove the nil entries from the list. The list doesn\'t need to be kept.

Thi

8条回答
  •  余生分开走
    2020-12-07 08:38

    each_with_object is probably the cleanest way to go here:

    new_items = items.each_with_object([]) do |x, memo|
        ret = process_x(x)
        memo << ret unless ret.nil?
    end
    

    In my opinion, each_with_object is better than inject/reduce in conditional cases because you don't have to worry about the return value of the block.

提交回复
热议问题