Can Ruby check 'nil' if I pass nothing into a function?

I have this weird behavior of my helper and suspect is has something to do with Is Ruby pass by reference or by value?, can I ask for your help to explain the behavior?




def helperA(object)
    if object == nil
    # do something if not nil 

However when nothing is passed into the helper(object does not have attribute_A), the 'if object == nil' doesn't catch the situation and continue running the code, which usually will cause error like "undefined method `length' for nil:NilClass" that's because of the later operation in helper.

My question is why is this happening?

1 answer

  • answered 2022-05-04 04:45 alilland

    # set object to default as nil
    def helperA(object = nil)
      return nil if object.nil? ## use object.blank? if you want empty strings, empty hashes and empty arrays to be caught in addition to nil
      # do something if not nil 

    you can also do something with what you are passing into the input

    helperA(@object&.attribute_A) # tells the function to treat the input as nil if the @object doesn't exist

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum