Perform map only when not nil?

Hop*_*eam 5 ruby ruby-on-rails ruby-on-rails-4

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
Run Code Online (Sandbox Code Playgroud)

vee*_*vee 8

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)