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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With