Perform map only when not nil?
ruby, ruby-on-rails, ruby-on-rails-4
Solution
A couple of other options:
Option 1 (checking for result of `split` when executing `map` on it):
names_list = names.try(:split, ",")
self.topics = names_list.map do |n|
Topic.where(name: n.strip).first_or_create!
end if names_list
Option 2 (using `try`, which will prevent the error):
self.topics = names.try(:split, ",").try(:map) do |n|
Topic.where(name: n.strip).first_or_create!
end
Problem
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 ```