ruby - Adding Possibly Nil Values -


i'm attempting write function in ruby sums parameters, however, if of parameters null, skip parameter , continue (unless values nil, in case return nil)

def sum(*vals)   sum = nil   vals.each |val|     value = eval(val)     unless value.nil?       sum.nil? ? sum = value : sum += value     end   end    sum end 

the issue parameters being sent in such way evaluation might cause nil error (i.e. input '2-nil'). if happens don't want break, continue adding.

so in other words, add parameters, , if there nil value or nil error in parameter, skip , continue adding.

so i've come 2 possible solutions.

  1. delay evaluation of parameters shielding them quotes , eval-ing them within function can catch these errors , continue working through parameters. shielding rather messy , gets particularly messy nested quotes. wondering if there cleaner way delay evaluation of parameters?

  2. locally override/create addition, subtraction, etc methods nilclass, such errors in parameter don't cause errors, instead produce nil. unsure how override/create methods nilclass, let alone limit use not occur in entire project.

if has insight options or other options, great help!

edit: example input might

bob = 2 fred = 3 tom = nil john = nil  sum(bob, fred+tom, john) => 2 

because fred+tom causes , error, i'd result in nil.

at moment solution

def sum(*vals)     sum = nil     vals.each |val|       begin         value = eval(val)         unless value.nil?           sum.nil? ? sum = value : sum += value         end       rescue typeerror, nomethoderror         nil       end     end     sum end  sum('bob', 'fred+tom', 'john') => 2 

however i'd not have shield every input

i got input array obtained string '2-nil-3.5-nil-1-0-10-nil'. if so, , if input array not big, can like

def sum(*vals)   vals.map { |val| eval(val) }.compact.inject(:+) end 

obviously in case might compact array before pass function , can avoid eval easily.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -