title: How to map and remove nil values in Ruby
body: <p>I have a <code>map</code> 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.</p>
  
  <p>This is what I currently have:</p>
  
  <pre class="lang-rb prettyprint-override"><code># A simple example function, which returns a value or nil
  def transform(n)
    rand &gt; 0.5 ? n * 10 : nil }
  end
  
  items.map! { |x| transform(x) } # [1, 2, 3, 4, 5] =&gt; [10, nil, 30, 40, nil]
  items.reject! { |x| x.nil? } # [10, nil, 30, 40, nil] =&gt; [10, 30, 40]
  </code></pre>
  
  <p>I'm aware I could just do a loop and conditionally collect in another array like this:</p>
  
  <pre class="lang-rb prettyprint-override"><code>new_items = []
  items.each do |x|
      x = transform(x)
      new_items.append(x) unless x.nil?
  end
  items = new_items
  </code></pre>
  
  <p>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?</p>