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)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Ruby, if something is not nil, it will return true in a boolean expression and its value in a calculation.
I’m not explaining it really well, but you can do something like this:
This is a more concise way of doing the ternary you were originally using.
Edit:
I actually like Jed Schneider’s answer better than my own. I’ll not copy it here, since his answer deserves the upvote for its elegance.