Question

Currently writing a class where methods that I am considering making private are spread throughout the code. Rather than adding a private line and copy-pasting everything below it, I want to do an inline declaration at the top of the class, such as private :foo, :bar.

However, whenever I try to declare a method with parameters as private inline, I get an error message. For instance, if I have a method foo(bar, baz), and try to declare it private with private :foo(bar, baz) I get error messages on the two parentheses, expecting kEND and = instead.

If I try to declare it with private :foo, I get told that there is no such method as foo in my code.

How can I do what I'm trying to do without getting these errors?

Was it helpful?

Solution

TL; DR private :foo must appear after the method is defined.

private's argument should be a symbol (e.g., :foo), not a call (e.g., foo(bar, baz))1.

Ruby class declarations are just code: statements are executed in the order they're written. Calling private :foo checks the class for a foo method. If it isn't defined yet, it's an error.


Updated for more-recent Ruby

The def keyword now returns the symbol of the method being defined, allowing:

private def foo; ... ; end

1 Unless it's a class method call returning a method symbol, an edge case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top