Are there more elegant ways to prevent negative numbers in Ruby?

后端 未结 5 2120
一向
一向 2021-01-17 23:53

Given that I\'d like to do the following calculation:

total = subtotal - discount

Because discount might be greater than

5条回答
  •  独厮守ぢ
    2021-01-18 00:30

    Some performance numbers:

                            user     system      total        real
    [i, 0.0].max        0.806408   0.001779   0.808187 (  0.810676)
    0.0 if i < 0.0      0.643962   0.001077   0.645039 (  0.646368)
    0.0 if i.negative?  0.625610   0.001680   0.627290 (  0.629439)
    

    Code:

    require 'benchmark'
    
    n = 10_000_000
    Benchmark.bm do |benchmark|
      benchmark.report('[value, 0.0].max'.ljust(18)) do
        n.times do |i|
          a = [-1*i, 0.0].max
        end
      end
    
      benchmark.report('0.0 if value < 0.0'.ljust(18)) do
        n.times do |i|
           a = 0.0 if -1*i < 0.0 
        end
      end
    
      benchmark.report('0.0 if value.negative?'.ljust(18)) do
        n.times do |i|
          a = 0.0 if (-1*i).negative?
        end
      end
    end
    

提交回复
热议问题