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

后端 未结 14 845
盖世英雄少女心
盖世英雄少女心 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条回答
  •  旧时难觅i
    2020-12-07 19:19

    Simple Answer:

    If you have n records, and you want to select and map based on condition then

    records.map { |record| record.attribute if condition }.compact
    

    Here, attribute is whatever you want from the record and condition you can put any check.

    compact is to flush the unnecessary nil's which came out of that if condition

提交回复
热议问题