Skip to content

Latest commit

 

History

History
37 lines (27 loc) · 722 Bytes

2020-06-26_ruby-2.7-adds-enumerable#filter_map.md

File metadata and controls

37 lines (27 loc) · 722 Bytes

Ruby 2.7 adds Enumerable#filter_map

Example:

enum = 1.upto(1_000)
enum.filter_map { |i| i + 1 if i.even? }
# => [3, 5, 7, 9, 11, 13, ...]

Previously we had to do:

enum = 1.upto(1_000)
enum.each_with_object([]) { |i, a| a << i + 1 if i.even? }
# => [3, 5, 7, 9, 11, 13, ...]

or

records = User.limit(10)
records.select { |user| user.is_admin? }.map{|user| "#{user.id} : #{user.name}"}
# => ["1: Jane", "4: Sam" ...]

or

enum = 1.upto(1_000)
enum.map { |i| i + 1 if i.even? }.compact
# => [3, 5, 7, 9, 11, 13, ...]

Thanks to @taylorthurlow, see: pjambet/til-rb#1

See: https://blog.saeloun.com/2019/05/25/ruby-2-7-enumerable-filter-map.html