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

后端 未结 14 844
盖世英雄少女心
盖世英雄少女心 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:27

    I usually use map and compact together along with my selection criteria as a postfix if. compact gets rid of the nils.

    jruby-1.5.0 > [1,1,1,2,3,4].map{|n| n*3 if n==1}    
     => [3, 3, 3, nil, nil, nil] 
    
    
    jruby-1.5.0 > [1,1,1,2,3,4].map{|n| n*3 if n==1}.compact
     => [3, 3, 3] 
    

提交回复
热议问题