简体   繁体   中英

Adding time after using a safe navigation operator

I have an object called event . One of the attributes is updated_at which is a date time . I want to add 15 seconds to updated_at to handle some tests that I'm doing.

It works when I do event.updated_at + 15.seconds

When testing, sometimes event is nil . So I handled it by using the safe navigator &. However, I'm unable to add the seconds now because I cannot chain an ordinary method call after a safe navigator operator.

So this will not work event&.updated_at + 15.seconds

Does anyone know how I can add time after using a safe navigator?

I guess I can do

if event
  event.updated_at + 15.seconds
end

But was looking for a better approach

You can use few different approaches, on your taste. But let's benchmark them!

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)

The results are in seconds. So сhoose the fastest or most attractive:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM