How to map and remove nil values in Ruby

前端 未结 8 1580
野性不改
野性不改 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:36

    If you wanted a looser criterion for rejection, for example, to reject empty strings as well as nil, you could use:

    [1, nil, 3, 0, ''].reject(&:blank?)
     => [1, 3, 0] 
    

    If you wanted to go further and reject zero values (or apply more complex logic to the process), you could pass a block to reject:

    [1, nil, 3, 0, ''].reject do |value| value.blank? || value==0 end
     => [1, 3]
    
    [1, nil, 3, 0, '', 1000].reject do |value| value.blank? || value==0 || value>10 end
     => [1, 3]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题