0

why is it said that in ruby instance method gets inherited by the subclass instead of instance variable of the superclass ? from the code one can clearly see that @order which is a instance variable in ruby is inherited by the subclass method Price_demand

class Management

    def price
        @OrderNo=4
        @Order =4
        puts "the price of order #{@OrderNo.to_s} is $40"
    end
    def exe
        puts "print #{@Order.to_s}"
    end

    def rant
        puts "please hurry with the order"
    end 
end


class Waiter < Management


    def Price_demand
        puts "the price of #{@Order.to_s} is $5"
    end
end


a=Waiter.new
a.price 
a.exe
a.Price_demand
puts a.instance_variables
2
  • ...instead of instance variable of the superclass - can you cite any documentation to support your statement? Commented Jan 25, 2016 at 11:51
  • it is there in a book 'Head First Ruby' at Page no 84 Commented Jan 25, 2016 at 11:54

2 Answers 2

1

There are no instance variables of the subclass or the superclass. Instance variables are properties of instances, not classes. That's why they are called "instance" variables, after all!

Once you understand that, your code should become clear: the instance variable belongs to a. It doesn't matter where the method that modifies it was defined.

[Note: Obviously, classes are instances, too (of class Class), so they can have instance variables of their own, but that is not what we are talking about here.]

Sign up to request clarification or add additional context in comments.

2 Comments

I am a little confused regarding variable declaration in Ruby inside class cant we declare any variable inside class like class Management holla="hi" end
Yes, sure, class bodies can have local variables. Note that local variables don't belong to objects, they belong to lexical scopes.
1

The instance variables will not come into existence until they are initialized through assignment. This is true whether the class is inherited or not. For instance, for the parent class Management, following is observed

m = Management.new
p m.instance_variables
#=> []
m.price
p m.instance_variables
#=> [:@OrderNo, :@Order]

Relating that to inheritance seems confusing, and I would say author of "Head First Ruby" book has unnecessarily confused the readers in that section of the book.


If you had a constructor in Management class that initialized instance variables to user supplied or default values, then, you would see those instance variables listed in response of instance_variables method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.