ChatGPT解决这个技术问题 Extra ChatGPT

How to map and remove nil values in Ruby

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.

This is what I currently have:

# A simple example function, which returns a value or nil
def transform(n)
  rand > 0.5 ? n * 10 : nil }
end

items.map! { |x| transform(x) } # [1, 2, 3, 4, 5] => [10, nil, 30, 40, nil]
items.reject! { |x| x.nil? } # [10, nil, 30, 40, nil] => [10, 30, 40]

I'm aware I could just do a loop and conditionally collect in another array like this:

new_items = []
items.each do |x|
    x = transform(x)
    new_items.append(x) unless x.nil?
end
items = new_items

But it doesn't seem that idiomatic. Is there a nice way to map a function over a list, removing/excluding the nils as you go?

Ruby 2.7 introduces filter_map, which seems to be perfect for this. Saves the need to re-process the array, instead getting it as desired first time through. More info here.
also Array has compact

J
Jason Axelson

You could use compact:

[1, nil, 3, nil, nil].compact
=> [1, 3] 

I'd like to remind people that if you're getting an array containing nils as the output of a map block, and that block tries to conditionally return values, then you've got code smell and need to rethink your logic.

For instance, if you're doing something that does this:

[1,2,3].map{ |i|
  if i % 2 == 0
    i
  end
}
# => [nil, 2, nil]

Then don't. Instead, prior to the map, reject the stuff you don't want or select what you do want:

[1,2,3].select{ |i| i % 2 == 0 }.map{ |i|
  i
}
# => [2]

I consider using compact to clean up a mess as a last-ditch effort to get rid of things we didn't handle correctly, usually because we didn't know what was coming at us. We should always know what sort of data is being thrown around in our program; Unexpected/unknown data is bad. Anytime I see nils in an array I'm working on, I dig into why they exist, and see if I can improve the code generating the array, rather than allow Ruby to waste time and memory generating nils then sifting through the array to remove them later.

'Just my $%0.2f.' % [2.to_f/100]

Why should it? The OP needs to strip nil entries, not empty strings. BTW, nil isn't the same as an empty-string.
Both solutions iterate twice over the collection... why not use reduce or inject?
It doesn't sound like you read the OPs question or the answer. The question is, how to remove nils from an array. compact is fastest but actually writing the code correctly in the start removes the need to deal with nils completely.
I disagree! The question is "Map and remove nil values". Well, to map and remove nil values is to reduce. In their example, the OP maps and then select out the nils. Calling map and then compact, or select and then map, amounts to making the same mistake: as you point out in your answer, it is a code smell.
Answer from @Ziggy should be accepted as a correct answer
t
the Tin Man

Try using reduce or inject.

[1, 2, 3].reduce([]) { |memo, i|
  if i % 2 == 0
    memo << i
  end

  memo
}

I agree with the accepted answer that we shouldn't map and compact, but not for the same reasons.

I feel deep inside that map then compact is equivalent to select then map. Consider: map is a one-to-one function. If you are mapping from some set of values, and you map, then you want one value in the output set for each value in the input set. If you are having to select before-hand, then you probably don't want a map on the set. If you are having to select afterwards (or compact) then you probably don't want a map on the set. In either case you are iterating twice over the entire set, when a reduce only needs to go once.

Also, in English, you are trying to "reduce a set of integers into a set of even integers".


Poor Ziggy, no love for your suggestion. lol. plus one, someone else has hundreds of upvotes!
I believe that one day, with your help, this answer will surpass the accepted on. ^o^//
+1 the currently accepted answer doesn't allow you to use the results of operations you performed during the select phase
iterating over enumerable datastructures twice if only on pass is needed like in the accepted answer seems wasteful. Thus reduce the number of passes by using reduce! Thanks @Ziggy
That's true! But doing two passes over a collection of n elements is still O(n). Unless your collection is so big that it doesn't fit in your cache, doing two passes is probably fine (I just think this is more elegant, expressive, and less likely to lead to bugs in the future when, say, the loops fall out of sync). If you like doing things in one pass too, you might be interested in learning about transducers! github.com/cognitect-labs/transducers-ruby
S
SRack

Ruby 2.7+

There is now!

Ruby 2.7 is introducing filter_map for this exact purpose. It's idiomatic and performant, and I'd expect it to become the norm very soon.

For example:

numbers = [1, 2, 5, 8, 10, 13]
enum.filter_map { |i| i * 2 if i.even? }
# => [4, 16, 20]

In your case, as the block evaluates to falsey, simply:

items.filter_map { |x| process_x url }

"Ruby 2.7 adds Enumerable#filter_map" is a good read on the subject, with some performance benchmarks against some of the earlier approaches to this problem:

N = 100_000
enum = 1.upto(1_000)
Benchmark.bmbm do |x|
  x.report("select + map")  { N.times { enum.select { |i| i.even? }.map{ |i| i + 1 } } }
  x.report("map + compact") { N.times { enum.map { |i| i + 1 if i.even? }.compact } }
  x.report("filter_map")    { N.times { enum.filter_map { |i| i + 1 if i.even? } } }
end

# Rehearsal -------------------------------------------------
# select + map    8.569651   0.051319   8.620970 (  8.632449)
# map + compact   7.392666   0.133964   7.526630 (  7.538013)
# filter_map      6.923772   0.022314   6.946086 (  6.956135)
# --------------------------------------- total: 23.093686sec
# 
#                     user     system      total        real
# select + map    8.550637   0.033190   8.583827 (  8.597627)
# map + compact   7.263667   0.131180   7.394847 (  7.405570)
# filter_map      6.761388   0.018223   6.779611 (  6.790559)

Nice! Thanks for the update :) Once Ruby 2.7.0 is released, I think it probably makes sense to switch the accepted answer to this one. I'm not sure what the etiquette is here though, whether you generally give the existing accepted response a chance to update? I'd argue this is the first answer referencing the new approach in 2.7, so should become the accepted one. @the-tin-man do you agree with this take?
Thanks @PeterHamilton - appreciate the feedback, and hope it will prove useful to plenty of people. I'm happy to go with your decision, though obviously I like the argument you've made :)
Yes, that's the nice thing about languages that have core teams who listen.
It's a nice gesture to recommend selected answers be changed, but it rarely happens. SO doesn't provide a tickler to remind people and people don't usually revisit old questions they've asked unless SO says there's been activity. As a sidebar, I recommend looking at Fruity for benchmarks because it's a lot less fiddly and makes it easier to make sensible tests.
C
Community

Definitely compact is the best approach for solving this task. However, we can achieve the same result just with a simple subtraction:

[1, nil, 3, nil, nil] - [nil]
 => [1, 3]

Yes, set subtraction will work, but it's about half as fast due to its overhead.
s
sawa

In your example:

items.map! { |x| process_x url } # [1, 2, 3, 4, 5] => [1, nil, 3, nil, nil]

it does not look like the values have changed other than being replaced with nil. If that is the case, then:

items.select{|x| process_x url}

will suffice.


F
Fred Willmore

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]

.blank? is only available in rails.
For future reference, since blank? is only available in rails, we could use items.reject!(&:nil?) # [1, nil, 3, nil, nil] => [1, 3] which is not coupled to rails. (wouldn't exclude empty strings or 0s though)
A
Abdullah Numan

You can use #compact method on the resulting array.

[10, nil, 30, 40, nil].compact => [10, 30, 40]

This solution was already provided here
p
pnomolos

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.


W
Wand Maker

One more way to accomplish it will be as shown below. Here, we use Enumerable#each_with_object to collect values, and make use of Object#tap to get rid of temporary variable that is otherwise needed for nil check on result of process_x method.

items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}

Complete example for illustration:

items = [1,2,3,4,5]
def process x
    rand(10) > 5 ? nil : x
end

items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}

Alternate approach:

By looking at the method you are calling process_x url, it is not clear what is the purpose of input x in that method. If I assume that you are going to process the value of x by passing it some url and determine which of the xs really get processed into valid non-nil results - then, may be Enumerabble.group_by is a better option than Enumerable#map.

h = items.group_by {|x| (process x).nil? ? "Bad" : "Good"}
#=> {"Bad"=>[1, 2], "Good"=>[3, 4, 5]}

h["Good"]
#=> [3,4,5]