S
S
severnik2021-12-20 13:36:58
ruby
severnik, 2021-12-20 13:36:58

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

or so
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

2 answer(s)
S
severnik, 2021-12-20
@severnik

Found this solution by poking around

nonil = (summa = a+b+c).nil? rescue true
unless nonil
  summa
end

R
Roman Mirilaczvili, 2021-12-20
@2ord

Just use the function.

def summa(cfs)
  cfs[5]+cfs[12]+cfs[10]+cfs[11]
end
sum = summa(cfs)

And separately read about error handling in Ruby.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question