In Ruby, is there an Array method that combines 'select' and 'map'?

后端 未结 14 796
盖世英雄少女心
盖世英雄少女心 2020-12-07 18:34

I have a Ruby array containing some string values. I need to:

  1. Find all elements that match some predicate
  2. Run the matching elements through a transfo
相关标签:
14条回答
  • 2020-12-07 19:30

    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]
    

    Here's a good read on the subject.

    Hope that's useful to someone!

    0 讨论(0)
  • 2020-12-07 19:30

    If you want to not create two different arrays, you can use compact! but be careful about it.

    array = [1,1,1,2,3,4]
    new_array = map{|n| n*3 if n==1}
    new_array.compact!
    

    Interestingly, compact! does an in place removal of nil. The return value of compact! is the same array if there were changes but nil if there were no nils.

    array = [1,1,1,2,3,4]
    new_array = map{|n| n*3 if n==1}.tap { |array| array.compact! }
    

    Would be a one liner.

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