Search code examples
rubyinheritanceattr-accessor

ruby restrict attr_accessor in subclass


I want restrict the access of superclass's method in subclass

class Parent
  attr_accessor :first_name, :last_name

  def initialize(first_name, last_name)
    @first_name, @last_name = first_name, last_name
  end

  def full_name
  @first_name + " " + @last_name 
  end

end

class Son < Parent
  attr_accessor :first_name

  def initialize(parent, first_name)
    @first_name = first_name 
    @last_name = parent.last_name
  end

  def full_name
    @first_name + "  " + @last_name 
  end
end


p = Parent.new("Bharat", "Chipli")
puts p.full_name

s = Son.new(p, "Harry")
s.last_name= "Smith"
puts s.full_name

here i am getting son's full name as "Harry Smith", but i want "Harry Chipli"


Solution

  • in the initialize method of the parent:

    @first_name, @last_name = [first_name, last_name]
    

    try this

    and:

    class Son
      def attr_reader :last_name
    
      def last_name=(name)
        @last_name ||= name
      end
    end
    

    this way it will only define the last name if the son doesn't have the name set from parent (good for orphans).