The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Ruby's Protected Access

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Dave Hoover

Posts: 93
Nickname: dsrhoov53
Registered: Mar, 2004

Dave Hoover is the Lead Consultant for Obtiva
Ruby's Protected Access Posted: Feb 23, 2007 10:12 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Dave Hoover.
Original Post: Ruby's Protected Access
Feed Title: Red Squirrel Reflections
Feed URL: http://redsquirrel.com/cgi-bin/dave/index.rss
Feed Description: Dave Hoover explores the psychology of software development
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Dave Hoover
Latest Posts From Red Squirrel Reflections

Advertisement
Jamis posted yet another nugget of wisdom. This one was about Ruby's method visibility, which can be tricky for people coming to Ruby from Java or C#. Jamis left one aspect of the protected access level as an exercise for the rest of us, so I figured I'd write up an example that helps illustrate when you would use protected vs. private.
class Sibling
  def ask(sib)
    sib.tell
  end
  
  def spy_on(sib)
    sib.secret # will always complain
  end

  protected

  def tell
    secret
  end
  
  private
  
  def secret
    "Charlie tooted"
  end
end

rose  = Sibling.new
ricky = Sibling.new

begin
  puts ricky.tell
rescue
  puts "Ricky will only tell another sibling"
end

begin
  puts rose.spy_on(ricky)
rescue
  puts "Ricky complains when Rose tries to find the secret"
end

puts rose.ask(ricky) # Ricky will tell if Rose asks nicely
One of the main differences for Java developers is that objects of the same class can't see each other's private methods.

Read: Ruby's Protected Access

Topic: Stupid extension of Ruby's arithmetic operators Previous Topic   Next Topic Topic: Ferret Pagination in Rails

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use