Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform map only when not nil?

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
like image 388
Hopstream Avatar asked Jan 02 '14 04:01

Hopstream


2 Answers

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
like image 119
vee Avatar answered Sep 19 '22 02:09

vee


That depends on what you want topics to become if names is actually nil. The most elegant solution would probably be to substitute an empty string where names is nil:

self.topics = (names || '').split(",").map do |n|
...

But that would assign an empty array to topics. If that's not what you want, you can wrap this with a nil check like this:

if names
  self.topics = ...
end

Or like this:

self.topics = names.split(",").map do |n|
  ...
end if names
like image 23
PinnyM Avatar answered Sep 19 '22 02:09

PinnyM