Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Ruby private method : a hack
David Boureau
David Boureau

Posted on • Edited on • Originally published atalsohelp.com

     

Ruby private method : a hack

article originally published here :https://alsohelp.com/blog/ruby-private-methods-hack

Private methods exist for a reason. However they can lead to tricky situations. Here is a quick hack about private methods in Ruby.

How to declare a private method

class Wolf  def scare    "scaring..."  end  private  def sleep    "sleeping.."  end  def eat    "eating.."  endend
Enter fullscreen modeExit fullscreen mode

All methods above the keyword "private" is considered as public, all methods below are considered as private.

Note that "private" here is not a keyword, but a method of the Kernel module.

What is a private method in Ruby

A private method cannot be called from the outside. Let's use a wolf in the IRB console. To use our Wolf above, simply copy/paste the class in the console (console will kindly accept carriage return)

$irb(main)> w= Wolf.new=>#<Wolf:0x00007fee2c760440>$irb(main)> w.scare=>"scaring..."$irb(main)> w.sleepTraceback(most recent call last):        1: from(irb):38:in`<main>'NoMethodError (private method `sleep' calledfor#<Wolf:0x00007fee2c760440>)
Enter fullscreen modeExit fullscreen mode

Now you got the idea. An object can decide to hide its internal behaviour, to ensure consistency. If you don't know what it this about, you can read aboutencapsulation, or read thisin-depth article about method visibility in Ruby.

Private methods in Ruby : the annoying parts

Why to hack a well-known OOP principle ? Because I find this privacy annoying. There are some corner cases :

  • You want just one other class to access the private method (but no other classes).
  • You want to test a private method because the regular way (test a private method through available public methods) do not work.
  • You have to think about hierarchy, and how "protected" method are handled, and if this hierarchy suits your needs.

Ruby is nice enough to avoid this mental headache : you can use the .send method to bypass the privacy rule.

$irb(main)> w.send('sleep')=> "sleeping.."
Enter fullscreen modeExit fullscreen mode

But why to loose so much energy... One time to define what is private or not, and another one to be sure we can go around the limitation.

Do we need this privacy anyway ?

Maybe yes. I'm thinking about Open-Source projects. Maintainers don't want the final user to manipulate private things, and break the internal behaviour (and raise some issue on Github...) about the Ruby gem. OOP is there for a reason.

But for your business, daily app, I think it's a burden. Often these applications are already private anyway. Think about a Rails app : no one can see your code. The /public folder is meant for frontend assets, not your codebase.

Thus I go around the "private" keyword by using an underscore as a suffix. Our wolf would now look like this :

class Wolf  def scare    "scaring..."  end  def _sleep    "sleeping.."  end  def _eat    "eating.."  endend
Enter fullscreen modeExit fullscreen mode

Each time I encounter an underscore, I know it means "hey be aware this is something fragile, in theory only the class, or fellow class, or test, may use it".

It was not invented here of course. As far as I can remember, Frameworks like VueJS use a double-underscore as a suffix, and I've seen this convention in other projects.

Private methods in Ruby recursive function

There one last use case for this kind of privacy : private arguments.

Let's say I have a recursive function, and I have to track the number of time the function is called to avoid an infinite loop :

defcountdown(n,_number_of_calls=0)ifn<1returnelsif_number_of_calls>5puts'too much calls, exiting'returnelseputsnendcountdown(n-1,_number_of_calls+1)end
Enter fullscreen modeExit fullscreen mode

Notice the _number_of_calls is not part of the public parameters :

$irb(main)> countdown(2)21=> nil
Enter fullscreen modeExit fullscreen mode

And if I exceed the number of call, I exit the recursion :

$irb(main)> countdown(10)1098765too much calls, exiting=> nil
Enter fullscreen modeExit fullscreen mode

Conclusion

private methods are necessary, it's a basic thing in OOP languages. However for your business app there is a nice shortener : the underscore - or any other convention you prefer.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
erikwhiting88 profile image
Erik
Sr. Software Engineer at CallRail building microservices to support 3rd party integrations. PhD student at the University of Nebraska studying bioinformatics, machine learning, and algorithms.
  • Email
  • Location
    Omaha, NE
  • Education
    BS CIS (2018), MS Software Engineering (2020), PhD Computer Science (in progress)
  • Pronouns
    He/Him
  • Work
    Sr. Software Engineer
  • Joined
• Edited on• Edited

But for your business, daily app, I think it's a burden. Often these applications are already private anyway. Think about a Rails app : no one can see your code.

Making functions private isn't about literal privacy, it's about enforcing the way a class is implemented. If you're working on a project where you're the only dev, sure,maybe private functions are a burden, but in a team context it's the cheapest and most basic way to enforce architecture. Public methods are your class's interface and should communicate how you want/expect that class to behave or be used, private methods are for handling the details, you don't want calling class's/methods touching them.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Rails & JS dev. Build products.
  • Location
    Nantes, France.
  • Joined

More fromDavid Boureau

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp