Rails 3.1: Ruby idiom to prevent .each from throwing exception if nil? -
solved: commentors noted, empty phonelist nil when should have been [].
is there way use .each
not throw error if object nil or empty (without adding additional nil/blank test?
it seems if phonelist.each |phone|
if phonelist empty, block should not executed.
but in view (haml) have - @myvar.phonelist.each |phone|
, if phonelist empty, throws nomethoderror.
i run lot, , workaround adding explicit check/branch .blank? seems there should easier way tell .each empty means nothing.
you're attempting smack band-aid on larger problem.
ruby has concept of nil; can't around it. if calling method on nil
, assuming valid, i.e., design assumes valid. question is: hole in design? why assumption incorrect?
the problem here not cannot call arbitrary methods on object not support it; problem data assumed valid when not case.
but in view (haml) have - @myvar.phonelist.each |phone| , if phonelist empty, throws nomethoderror.
no. if phonelist
is not object implements .each
throws error. different.
you can initialize empty array if null, i.e., phonelist ||= []
, prefer design ensures valid data whenever possible.
Comments
Post a Comment