Answer the question
In order to leave comments, you need to log in
How to check for nil in a Ruby variable that has been assigned a certain formula?
How can you test a certain formula for nil and at the same time assign this formula to a variable for further use without having to write the expression of the formula again into the variable? The formula is quite long and I don’t want to duplicate it in the code again.
Separately, I understand how to do the check and then the assignment.
The formula expression in the example below is cfs[5]+cfs[12]+cfs[10]+cfs[11]
nonil = (cfs[5]+cfs[12]+cfs[10]+cfs[11]).nil? rescue true
unless nonil
summa = cfs[5]+cfs[12]+cfs[10]+cfs[11]
end
unless ((cfs[5]+cfs[12]+cfs[10]+cfs[11]) rescue nil).nil?
Answer the question
In order to leave comments, you need to log in
Found this solution by poking around
nonil = (summa = a+b+c).nil? rescue true
unless nonil
summa
end
Just use the function.
def summa(cfs)
cfs[5]+cfs[12]+cfs[10]+cfs[11]
end
sum = summa(cfs)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question