j4ehsq
Last Updated: February 25, 2016
·
950
· rwz
Userpic

Distinguishing nil argument from no argument in ruby.

Let's say you want to create a method that accepts an argument which can be nil, or no arguments at all. And you need your method to distinguish nil argument from no argument. Something like this:

inspector = Inspector.new
inspector.inspect       # => You've passed nothing
inspector.inspect nil   # => You've passed nil
inspector.inspect :foo  # => You've passed something

So, here are two simple ways of doing that:

class Inspector
  # Using a vanilla object for default value.
  # This object is not equal to anything except for
  # itself, making it a perfect choice for a default
  # value placeholder like here:
  BLANK_VALUE = Object.new

  def inspect(value = BLANK_VALUE)
    if BLANK_VALUE == value
      puts "You've passed nothing"
    elsif value.nil?
      puts "You've passed nil"
    else
      puts "You've passed something"
    end
  end

  # Another approach is to accept an array of arguments
  # and to check it's length
  def inspect(*args)
    if args.empty?
      puts "You've passed nothing"
    elsif args.first.nil?
      puts "You've passed nil"
    else
      puts "You've passed something"
    end
  end
end
Say Thanks
Respond