Re:Better Know a Ruby Thing: Singleton Classes
by dragonwriter on Saturday February 01, 2025 @12:01AM
(#42895801)
> It's worth noting that two of such ways will, perhaps unintuitively, ignore the `private` keyword.
No, this explanation is wrong, because there isn't actually a `private` keyword, only the Module#private method [0] which, when called with no arguments, changes the visibility of future methods defined in the target module.
Those examples call the `Module#private` method with no arguments in one context changing the visibility of future methods defined in that context, and then use an explicit prefix to define methods in a different context.
When you don't forget that `private` is a private instance method on Module and not a keyword, the behavior is much simpler to understand.
Re:Better Know a Ruby Thing: Singleton Classes
by lcnPylGDnU4H9OF on Saturday February 01, 2025 @12:42PM
(#42900255)
Thanks for the correction! It can be hard to appreciate how true “everything is an object” is.
Re:Better Know a Ruby Thing: Singleton Classes
by dragonwriter on Saturday February 01, 2025 @02:20PM
(#42901255)
That and how, between block arguments and optional parens on method invocation, Ruby allows (and the core exploits this) defining lots of constructs that look like keyword-based syntax as methods.
It's worth noting that two of such ways will, perhaps unintuitively, ignore the `private` keyword.
That will define a public method `:foo` on each of `self`'s and `x`'s singleton classes. If you want the method to be private, either 1) explicitly make the method private using `Class#private` or `Class#private_class_method` or 2) use the `class << self` (or `class << x`) syntax in order for the `private` keyword to work as expected. > The eternal question… Why is Ruby like this?Joy! :) I'm pretty sure matz would agree.