Best way to write this calculation in Ruby?

What is the best way to write this calculation in Ruby?

amt = self.alt_inv - (self.alt_tax ? self.alt_tax : 0)
    - (self.alt_freight ? self.alt_freight : 0)
    - (self.misc1_amt ? self.misc1_amt : 0)
    - (self.misc2_amt ? self.misc2_amt : 0)
+3
source share
7 answers

In Ruby, if something is not nil, it will return true in the boolean expression and its value in the calculation.

I am not explaining this very well, but you can do something like this:

amt = alt_inv - 
  (alt_tax     || 0) -
  (alt_freight || 0) -
  (misc1_amt   || 0) -
  (misc2_amt   || 0)

This is a shorter way to make the triple you originally used.


Edit:

I really like that Jed Schneider answers better than mine. I will not copy it here, as its answer deserves to be enhanced by its elegance.

+8
source

amt - alt_inv, , alt_inv. reduce . compact nil .

, , , , .

attributes = [alt_tax, alt_freight, misc1_amt, misc2amt]
amt = alt_inv - attributes.compact.reduce(:+)

: http://apidock.com/ruby/Enumerable/reduce

compact: http://apidock.com/ruby/Array/compact

+6

, 0, , . ​​ , . ?

amt = alt_inv - alt_tax - alt_freight - misc1_amt - misc2_amt 
+5

, self.alt_tax alt_tax self.

|| , , , :

alt_tax ? alt_tax : 0

:

alt_tax || 0
+1

Jed, , .

compact inject ( reduce) Ruby:

amt = [alt_tax, alt_freight, misc1_amt, misc2_amt].inject(alt_inv) do |result, attribute|
  result - (attribute || 0)
end

amt = alt_inv - [alt_freight, misc1_amt, misc2_amt].compact.inject{|sum, n| sum + n }

inject(&:+), . Rails, sum .

+1

:

1) Ruby makes assumptions about the end of instructions.

As

amt = self.alt_inv - (self.alt_tax ? self.alt_tax : 0)

In itself is the correct instruction, you need to either save the minus on the previous line, or exit the new line.

2) Ruby assumes the ego as the owner, with the exception of the left-side assignments. I suggest:

amt = alt_inv - 
  (alt_tax     ? alt_tax     : 0) -
  (alt_freight ? alt_freight : 0) -
  (misc1_amt   ? misc1_amt   : 0) -
  (misc2_amt   ? misc2_amt   : 0)
0
source
amt = alt_inv - alt_tax.to_f - alt_freight.to_f - misc1_amt.to_f - misc2_amt.to_f
nil.to_f = 0.0
0
source

Source: https://habr.com/ru/post/1761577/


All Articles