vishless
vishless

Reputation: 898

Does 'attr_reader' make a local variable available throughout a class?

Why is the type variable available in the is_a_peacock? method in the following?

class Animal
    attr_reader :type

    def initialize(type)
        @type = type
    end

    def is_a_peacock?
        if type == "peacock"
            return true
        else
            return false
        end
    end
end

an = Animal.new('peacock')
puts an.is_a_peacock? # => true

Why does commenting out the initialization of @type make type unavailable?

class Animal
    attr_reader :type

    def initialize(type)
        #@type = type
    end

    def is_a_peacock?
        if type == "peacock"
            return true
        else
            return false
        end
    end
end

an = Animal.new('peacock')
puts an.is_a_peacock? # => false

Upvotes: 0

Views: 175

Answers (3)

sawa
sawa

Reputation: 168199

Why is the type variable available in the is_a_peacock? method in the following?

Your presupposition to this question does not hold. type inside the method body of is_a_peacock? is not a local variable. It is a method call.

Why does commenting out the initialization of @type make type unavailable?

It does not. The method type is available, which returns the value of @type, which is nil by default.

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230471

"Why does commenting out the initialization of @type make type unavailable?"

It does not. Method type is available. Just not initialized. Because you commented that out.

If method type wasn't available, your program would crash. (As it does when you comment out the attr_reader).

Upvotes: 1

Henrik N
Henrik N

Reputation: 16294

You can think of attr_reader :type as doing this for you:

def type
  @type
end

But it does not automatically assign instance variables based on what you pass into the initializer, like you seem to assume it would do.

Since you no longer do @type = type, @type stays at its default value of nil. Every instance variable is nil by default.

On a side note, instead of

   if type == "peacock"
        return true
    else
        return false
    end

you can write just

   type == "peacock"

Upvotes: 1

Related Questions