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

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

    If you have a select that can use the case operator (===), grep is a good alternative:

    p [1,2,'not_a_number',3].grep(Integer){|x| -x } #=> [-1, -2, -3]
    
    p ['1','2','not_a_number','3'].grep(/\D/, &:upcase) #=> ["NOT_A_NUMBER"]
    

    If we need more complex logic we can create lambdas:

    my_favourite_numbers = [1,4,6]
    
    is_a_favourite_number = -> x { my_favourite_numbers.include? x }
    
    make_awesome = -> x { "***#{x}***" }
    
    my_data = [1,2,3,4]
    
    p my_data.grep(is_a_favourite_number, &make_awesome) #=> ["***1***", "***4***"]
    

提交回复
热议问题