首页 > 解决方案 > 使用安全导航算子后增加时间

问题描述

我有一个名为event. 其中一个属性是updated_atwhich 是date time. 我想增加 15 秒来updated_at处理我正在做的一些测试。

当我这样做时它会起作用event.updated_at + 15.seconds

测试时,有时eventnil. 所以我使用安全导航器处理它&.但是,我现在无法添加秒数,因为我无法在安全导航器运算符之后链接普通方法调用。

所以这行不通event&.updated_at + 15.seconds

有谁知道使用安全导航器后如何增加时间?

我想我能做到

if event
  event.updated_at + 15.seconds
end

但一直在寻找更好的方法

标签: ruby-on-railsruby

解决方案


您可以根据自己的喜好使用几种不同的方法。但是让我们对它们进行基准测试!

n = 10_000_000

Benchmark.bm do |test|
  test.report('if:')       { n.times { nil.updated_at + 15.seconds if nil } }
  test.report('unless:')   { n.times { nil.updated_at + 15.seconds unless nil.nil? } }
  test.report('& + send:') { n.times { nil&.updated_at&.send(:+, 15.seconds) } }
  test.report('& + try:')  { n.times { nil&.updated_at.try(:+, 15.seconds) } }  
end  

#              user       system     total        real
# if:        0.390000    0.000000   0.390000   (0.392020)
# unless:    0.570000    0.000000   0.570000   (0.569032)
# & + send:  0.380000    0.000000   0.380000   (0.381654)
# & + try:   13.950000   0.000000  13.950000   (13.959887)

结果以秒为单位。所以选择最快或最有吸引力的:)


推荐阅读