Arivarasan L
Arivarasan L

Reputation: 9988

ruby inheritance

How to implement inheritance in ruby for the following?

class Land
  attr_accessor :name, :area
  def initialize(name, area)
    @name = name
    @area = area
  end
end

class Forest < Land
  attr_accessor :rain_level
  attr_reader :name

  def name=(_name)
    begin
      raise "could not set name"
    rescue  Exception => e
            puts e.message  
        end
  end

  def initialize(land, rain_level)
    @name = land.name
    @rain_level = rain_level
  end
end

l = Land.new("land", 2300)
f = Forest.new(l, 400)
puts f.name # => "land"    

suppose when i change name for land l, then it should change for sub class also

l.name ="new land"
puts f.name # => "land"

what expected is puts f.name # => "new land"

Upvotes: 1

Views: 1018

Answers (2)

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31458

It seems to me that this is not actually inheritance in the OO sense. If you change Forest so that it holds a reference to the Land then you will get the behavior you wanted.

class Forest
  attr_accessor :rain_level

  def name
    @land.name
  end

  def initialize(land, rain_level)
    @land = land
    @rain_level = rain_level
  end
end

Upvotes: 2

Joshua
Joshua

Reputation: 2982

This is kind of an interesting thing you want to build.

Summarizing you want to have two objects that share a value but only one is allowed to edit the value, the other one is only allowed to read it.

I think the easiest way to implement this is in your case to implement a new getter in Forest which returns land.name. By writing l.name = 'meow' will f.name return moew too because it holds a reference to l.

Hope this helps.

Upvotes: 0

Related Questions