June February 2016

is ruby nil checking necessary when call "respond to" method?

I am new to Ruby and I got a question: is the nil checking necessary in following code? would you please explain a little bit? Thank you in advance!!if you think this is too easy to answer, would you please tell me the document( or link) that I need check to solve my doubts? this is the original question: within the say_hi method, the author checks if the instance variable @names is nil. Why is this check done? Is the check really needed in the MegaGreeter class as it is written? Why or Why not?

class MegaGreeter
  attr_accessor :names

  # Create the object
  def initialize(names = "World")
    @names = names
  end



     # Say hi to everybody
      def say_hi
        if @names.nil?
          puts "..."
        elsif @names.respond_to?("each")
          # @names is a list of some kind, iterate!
          @names.each do |name|
            puts "Hello #{name}!"
          end
        else
          puts "Hello #{@names}!"
        end
      end

  # Say bye to everybody
  def say_bye
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("join")
      # Join the list elements with commas
      puts "Goodbye #{@names.join(", ")}.  Come back soon!"
    else
      puts "Goodbye #{@names}.  Come back soon!"
    end
  end
end


if __FILE__ == $0
  mg = MegaGreeter.new
  mg.say_hi
  mg.say_bye

  # Change name to be "Zeke"
  mg.names = "Zeke"
  mg.say_hi
  mg.say_bye

  # Change the name to an array of names
  mg.names = ["Albert", "Brenda", "Charles",
              "Dave", "Engelbert"]
  mg.say_hi
  mg.say_bye

  # Change to nil
  mg.names = nil
  mg.say_hi
  mg.say_bye
end

Answers


Chris Wilson February 2016

The way the initializer is set up, @names should never be nil because of the default value of 'World' being assigned if nothing is provided.

The problem is the public attr_accessor in the MegaGreeter class, which you can read about this method here. It creates a setter method on the @names instance variable, meaning it can be changed to anything, including nil.

Post Status

Asked in February 2016
Viewed 3,250 times
Voted 4
Answered 1 times

Search




Leave an answer