`map` based on condition
Do a select
first
clients.select{|c| c.type == 'tablet'}.map(&:ip)
Ruby 2.7+
Ruby 2.7 is introducing filter_map
for this exact purpose. It's idiomatic and performant, and I'd expect it to become the norm very soon.
For example:
numbers = [1, 2, 5, 8, 10, 13]
enum.filter_map { |i| i * 2 if i.even? }
# => [4, 16, 20]
Here's a good read on the subject.
Hope that's useful to someone!
Answer is as simple as that:
clients.map { |client| client.ip if client.type == 'tablet' }.compact
Mapping with condition will give nils for clients which failed the condition, for that only we kept compact
, which will actually flush the nil values.