My Ruby Epiphany
Private methods in Ruby
Rope Light by Unsplash is licensed under the Creative Commons Zero Licence
I’ve been using and teaching Ruby for many years now, but I recently had an epiphany about indentation.
I’ve long been annoyed by private
and its lesser-used siblings protected
and public
because I saw them as “keywords” that change the context.
class Idea
def example_public_method
...
end
private
def example_private_method
...
end
end
I’ve described it before as changing how the parser sees methods as it reads from the top down.
This never seemed very “Rubyish” to me. I had thought a block would make more sense:
class Idea
def example_public_method
...
end
private do
def example_private_method
...
end
end
end
But my recent epiphany made me realize I’ve been wrong the whole time:
private
is to class
and end
as
else
is to if
and end
.
if surprised?
# do something
else
# do something else
end
This also changes my mind in how we should indent it.
class Idea
def example_public_method
...
end
private
def example_private_method
...
end
end
I don’t know why it took me so many years to realize this. Anyone else with me?
Comments
This also means I disagree with what the community-built Ruby styleguide suggests but this is far from the first thing I’ve disagreed with.
I read else and rescue as alternate behavior, and private isn’t alternate behavior.
@chrismo: But I think it is different behavior. You’re defining methods as private instead of public. That’s a difference in how they behave.
Yeah I’ve been doing that for years until 2.0 let you actually prefix def with it:
private def
…
end
No matter how far down the file you are you always know right away if the method is public or private.
I think it’s a tough adjustment for anyone who first encountered ‘public’ and ‘private’ in C** or Java. It was for me.
Now let me submit to you a third way of thinking about it:
‘public’ and ‘private’ are mode-switching commands sent to the class object.
@Avdi Grimm: I like that explanation, but is there anywhere else in Ruby that sort of thing happens? I can’t think of any.