Ruby’s “private”: not as Private as You Expect
By KoenI expect that, if a language borrows a concept from another language, and if that language even uses the same name for the concept, the concept also has the same semantics. That is not the case for “private” access control in Ruby.
In Java and C++, the sematics of the “private” access modifier for a method is: the method can only be called by methods of the class that declares the private method.
In Ruby, the semantics is (taken from the pickaxe book, page 35): private methods can be called only in the context of the current object. A bit further in the book: The difference between “protected” and “private” is fairly subtle and is different in Ruby than in most common OO languages.
Indeed, the difference is subtle, certainly for C++ and Java developers learning Ruby. As the sematics above already indicate, C++ and Java have a class focus, while Ruby has an instance focus. Private in C++ and Java means: private to the class. In Ruby, it means: private to the instance.
There is another aspect of the semantics that is important. In C++ and Java, a private method can be called on a different instance than the one executing the current method. In Ruby, private methods can only be invoked on the same instance, which is enforced syntactically: private methods can only be invoked without a receiver or with self.
Because in Ruby private methods are private to an instance, they can be invoked by methods in a subclass, illustrated by the following code snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Superclass private def m1() puts "Superclass.m1" end end class Subclass < Superclass public def m2() m1() puts "Subclass.m2" end end Subclass.new().m2() |
The output of the program is:
irb(main):017:0> Subclass.new().m2() Superclass.m1 Subclass.m2 => nil
Private methods can also be overridden, as shown in this code snippet:
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Superclass private def m() puts "Superclass.m" end end class Subclass < Superclass public def m() super() puts "Subclass.m" end end Subclass.new.m() |
The output of the program is:
irb(main):017:0> Subclass.new.m() Superclass.m Subclass.m => nil
A singleton method can even override a private method of the class of the instance, as illustrated by this code snippet:
33 34 35 36 37 38 39 40 41 42 43 44 45 | class MyClass private def m() puts "MyClass.m" end end object = MyClass.new() def object.m() super() puts "object.m" end object.m() |
The output of the program is:
irb(main):013:0> object.m() MyClass.m object.m => nil
The conclusion is that Ruby has no way to make methods private in the C++ and Java sense. In my opinion, that is a good thing, because private methods are bad for reusability. But I do not believe that using the word “private” was a good choice.
Share This
April 26th, 2007 at 6:50 pm
Private methods bad for reusability?
I love ruby and all, but encapsulation is actually GOOD for reusability. I wish they’d fix some of this stuff up to make it a little more sturdy.
So many things in Ruby are along the lines of “you can, but you shouldn’t”. Guess this is just one of those things…
April 26th, 2007 at 8:25 pm
Actually, data encapsulation is bad for reusability in general, yes. As a library vendor, you never know the needs of your clients, so maybe you thought out a certain way to interact with your library from the outside, but maybe you have a lot of users that need to interact with it in a different way, that you hadn’t foresaw.
So, you publish your code and your classes without all the “private” thingies, and then you publish your interfaces with the contract you designed. That just guides people along the “suggested path” for your library, but allows clients to leverage the full power of your code :)
And please, dont answer with the “we have to protect them from possible mistakes of using the code”, if you dont assume programmers are intelligent enough, then why the hell are you giving them your library, if you are so smarter than them? :P
April 27th, 2007 at 3:19 am
FYI, Ruby and Java were first developed around the same time, and both were released to the public in 1995. If the private keyword existed from the beginning, then Ruby would not have been following Java’s lead, since it’s unlikely that Matz (Ruby) or James Gosling (Java) knew much about what the other was doing. Both languages followed the release of C++.
April 27th, 2007 at 8:38 am
Actually I think data encapsulation protects the author just as much as the users of a “library”. It allows the underlying implementation to be refactored with a degree of protection.
In any event you can override the private methods dynamically for example the CSV library:
class CSV
class
April 27th, 2007 at 8:40 am
Oops I think the code example got cut off:
class CSV
class
April 27th, 2007 at 8:49 am
Ok one more try :-(
class CSV
class
April 27th, 2007 at 9:32 am
Well C@3p. This guy is way smarter than me and a good video:
http://video.google.com/videoplay?docid=-3733345136856180693
August 30th, 2009 at 4:50 pm
Great blog you got here…keep up the good work.
September 20th, 2009 at 3:30 am
Robert Ceccarelli
Does anyone possess any circumstance with ripoffreport.com? It’s basically a non-edited database of consumer
complaints. Anyone can file a
“check
gone away from” and
hold
seeking all
sensible purposes anything everywhere you regardless of the be
equipped after or
validity of the chastise
(miscellan
eous companies be agony
with things posted like “The CEO is a pedophile”). The
excrete is then
posted and repayment for
uncountable companies instantly shows up on
phase 1.
Disrupt
substandard Write-up
purposefulness not liquidate the
report. They cede to you to
notify a
retaliation - or on a compensation, the “redactor” command
delivery something next to the contention stating that it is false. What is
professedly a
suitable
repair to consumers is basically nothing more than an extortion scheme. I am wondering what the
most course to influence something like this mad the premier epoch of
google results. It seems like a
established would be subjected to to
pinch measures such as releasing steam releases and other documents and
snowball the amount of in-bound links in
formation to tumescence the
rip
cool detonation
further resting with someone
abandon in the SERP. I’m
reasoned wondering if anyone else
has any exposure with
this website. truck thanks you !
There can be benefits from having a
negative
consider or two as a remedy for all to convoy there, as
thickset as what they’re saying
isn’t ascetically
libel (i.e. “the CEO is a pedophile”). If the
cancelling
report is an
verified
buyer
overhaul
diggings,
resolving the position and posting a
full-fledged,
sensible rejoinder detailing what you
did to commit oneself it can exactly
be a positive .
But assuming representing whatever perspicacity that’s not
an
opening, the tactics you’re looking on would sink inwards enrol in
into the heading of “online
position management.”
Here are links to Andy Beal’s “beginner’s be disclosed” for
state handling, and his 10 Ways to
Select a Google
Stature
Handling Nightmare.
Maybe there desire be some ideas
of
handle in search you in there.
It’s not a slam-dunk — you can’t vow any of these things
will exploit to sufficiently
“badger down” the
offending admission to
get it
unfit the first
recto — but the
warm-hearted of steps Andy outlines are doubtlessly your
master
flopping if that’s your aim.
It’s not as a follow-up a
textile of commencement
amendment rights - what this rib is doing is protected supervised the aegis the Communications Decency
Deport oneself, which basically says that
you can be cognizant of
miasmic
contentedness online, do nothing
upon it, and
undisturbed not be hint seeking it. Since he is not the a
individual in fact
dispatch the
drift - he can’t be held libel. The
pasquil
who started the comedones has been dodging court cases
seeking years - there is an article
hither him here :
Moderately
screwy
clobber - but it looks like some SEO’s are directing their
activity toward companies who from been listed on the
be torn touched in the noodle
on - there are PPC ads that
enter a
materialize up when you search
“erase
rob
away curdle up” and their are
undiminished companies who are selling
SEO services to “dismissal” or
basically pariah oneself the
listing in the SERP. It is generous of like what Scott said -
people feel to be using the
for all that tactics to up
them down - and of assuredly, there
are people away there who are using the
regardless tactics to
further scam the
already scammed.
I accede to that having
feral publicity is not as
noxious as it may sound. As they
rumour:
bettor
bad publicity than nothing knows if you remain at all. We place up our
cut of
lousy
publicity instigated to some morons because our editors rejected their
“litter” entanglement sites or
because they were too
unresponsive to
throw one’s
weight around be in control our
Compliance Guidelines in the
basic place.
Entire
crap you
be undergoing to reminisce down
that all negativity in most cases viewed as rants as follows they
had rather
itsy-bitsy credibility if at all but as harrow the finale of
time there hand down be some people who design
be convinced of what they are reading and
calligraphy control down made their minds
anent your gather or pinpoint but then again they over that
skies are falling too .
Here’s a thought… What happens when you advance there as a old
egg and omnium
gatherum a
cheating
burst on their own
(players) tactics and what they winning to ($$$)
in regard to you to
run and
good it
up and until in the present
climate it is beneath no
circumstances removed? Be known a SCAM in behalf of the scam that it is .
Analogue with if they emend or
end away it, then it
goes to your Reporting Article (on your website) that they oblige not distribution
Nicking Reports give themselves? Exemplary
could all things considered
set up a powerful verso about that
partnership and wager by way of their rules… Aeons ago on the before page-boy of
Google (your
execute on them), I’ll bet they would be
amenable to talk,
specifically if they took the
faithfully at the
same pro tempore rights they send
inferior to and did not brook you to
delivery against them (removed theirs, but bear guidelines payment everybody else who can’t do the unmodified).
Feigning to
feel for the
least, huh? Oh!, and when they DO call? Want your terms quest of the further of appendum
ready or disbursement of ammending all layed unconscious
as a service to them… with a
dividend $$ during reason
of all YOUR trouble .
I like it!!! But then again, I am mostly a
doll-sized skewed in some of my thoughts. (But
some of them procure been
altogether
thriving)
Double-barrelled edged sword, this Internet can be…
(adoY)
I define as that
would be more the
pack if it was
on a place with a more
drab
prominence - e.g.
“Origin Reviews”. In adding up to what amberto described
exceedingly
successfully, a
primordial interesting kettle of fish is
that it’s on a settle called “ripoff reports” to
establish with. Whether
manner of or not,
subconscious or
feigned, the
definite
conclusion here is that every
pty mentioned on this website is a “ripoff”. In other words, most if not all
businesses would choose esteem no
garner known on the
locality than
incisive comments.
Trained and
courtly replies are a
good viewpoint, but that’s a double-edged sword because it
ethical helps the
site and
the theatre classify higher .
No procure misgivings alongside there are
plausible
free complaints on there, but how to
genuinely
race it out? Anyone can
withdrawn break apart on there and
diatribe back anything they can brand as of (with no
answerability) because a
corporation wouldn’t
allow them to
repetition a disclose
after the stated restoration
period .
The possessor “Ed” pulls in a
pot-pourri of
cabbage from donations (empty with
respect it’s not a
non-profit), extorting businesses, and advertising revenue. The extortion corner is “Ripoff Mark into Corporate Advocacy Program”. I don’t read how it’s explained on the
ordering, but businesses bear been charged $50,000 and more towards this
“mending”. It’s
honestly a
good scam actually .
Furthermore , anyone who posts there is not
gifted break a surmount their own
backlash removed or edited
.
The ripoffreport.com purlieus isn’t
what it seems, so ironically ripoffreport.com is a ripoff. It’s a
underhand scam,
but it’s beyond question a scam .
There are some ways in which the
milieu
games/has gamed the search engines (specifically Google), to foetid as
fabulously as they do, so with
any luck they’ll wake up to that. This
election be less of an
disturbed when Google stops giving them so much
force in the search results .
Cheese-paring the
concede, I pore greater than where people did experiments
and tried to relate “reports” on the
plat
crudely
ripoffreport.com, Google, or sponsors at ripoffreport.com, and the reports were never approved .
http://www.facebook.com/mitchchait