gpt4 book ai didi

ruby-on-rails - 只有当不是 nil 时才执行映射?

转载 作者:数据小太阳 更新时间:2023-10-29 07:12:03 25 4
gpt4 key购买 nike

如果 namesnil,则以下中断。我怎样才能让这个 map 只有在它不是 nil 时才执行?

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

最佳答案

其他几个选项:

选项 1(在其上执行 map 时检查 split 的结果):

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

选项 2(使用 try,这将防止错误):

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

关于ruby-on-rails - 只有当不是 nil 时才执行映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20876456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com