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

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

    No, but you can do it like this:

    lines.map { |line| do_some_action if check_some_property  }.reject(&:nil?)
    

    Or even better:

    lines.inject([]) { |all, line| all << line if check_some_property; all }
    

提交回复
热议问题