Skip to content

Instantly share code, notes, and snippets.

@rbishop
Created July 15, 2014 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbishop/40138b6082ba26c681fc to your computer and use it in GitHub Desktop.
Save rbishop/40138b6082ba26c681fc to your computer and use it in GitHub Desktop.
Inheritance and private vs protected
class Parent
def initialize(name)
@name = name
end
private
attr_accessor :name
end
class Child < Parent
def parents_name(parent)
parent.name
end
end
bob = Parent.new("Bob")
betty = Child.new
betty.parents_name(bob)
#=> NoMethodError: private method `name' called for #<Parent:0x007fbf240a2770 @name="Bob>
class Parent
def initialize(name)
@name = name
end
protected
attr_accessor :name
end
class Child < Parent
def parents_name(parent)
parent.name
end
end
bob = Parent.new("Bob")
betty = Child.new
betty.parents_name(bob)
#=> "Bob"
@sgrif
Copy link

sgrif commented Jul 16, 2014

I see. This has nothing to do with inheritance, you can demonstrate the same problem without a child class.

@rbishop
Copy link
Author

rbishop commented Jul 16, 2014

@sgrif How would you go about doing that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment