我遇到这样的情况:
# self refers to an instance of a Book class
self.author = instance_of_author_class #returns instance
self.author.name = instance_variable_in_author_instance #returns string
# this is an instance method of the Book class:
def author_name
self.author ? self.author.name : nil #returns string or nil
end
此代码运行良好,因为它首先检查是否有author
集,然后返回其名称,如果没有设置作者,则返回nil
。
然而,我希望能够用更少的代码来实现这一点,因为我发现我经常处于这样的情况,我想">如果存在,只返回东西"。我不喜欢在简单地返回之前测试它。||
OR表达式看起来会非常完美。
def author_name
self.author.name || nil
end
如果self.author.name
以某种方式预先初始化为false
或nil
,这将非常有效,但不幸的是,如果author
没有设置为某个有效实例(并且该有效实例还定义了name
方法(,那么我将得到:
NoMethodError:
undefined method `name' for nil:NilClass
不幸的是,ruby似乎并没有将这样的错误视为false
,它停止了执行。
关于如何实现这个目标,有什么想法吗?
(还添加了javascript stackoverflow标记,因为我也欢迎javascript解决方案!(
您可以使用Ruby在2.3:中引入的安全导航操作符
def author_name
author&.name
end
请注意,在您的示例中不需要self
。
或者,当您使用RubyonRails时,您可能希望使用delegate
:
delegate :name, to: :author, prefix: true, allow_nil: true