Perform map only when not nil?

Viewed 8880

The following breaks if names is nil. How can I have this map execute only if it's not nil?

self.topics = names.split(",").map do |n|
  Topic.where(name: n.strip).first_or_create!
end
6 Answers

Finally in ruby 2.7 you can use

['Moscow', 'Norilsk'].map do |city|
  city if city == 'Norilsk'
end
=> [nil, "Norilsk"]

['Moscow', 'Norilsk'].filter_map do |city|
  city if city == 'Norilsk'
end
=> ["Norilsk"]
Related