From: "matheusrich (Matheus Richard) via ruby-core" Date: 2024-01-22T20:29:02+00:00 Subject: [ruby-core:116373] [Ruby master Feature#20202] Memoized endless method definitions Issue #20202 has been updated by matheusrich (Matheus Richard). I understand why some people might not like endless methods, but I don't think they're purely one-line methods (read @zverok 's [take on this](https://zverok.space/blog/2023-12-01-syntax-sugar5-endless-methods.html)). Also they're already merged, so I guess it's out of topic dicussing that. > I am not sure it is that common. It is perhaps more common in rails-specific code I'd argue that using a helper object like that is pretty common even outside Rails code. Sometimes it is done via a macro to delegate, instead of an explicit method like I did. > Personally, though, I am not a big fan of these condensed one-liner variants. Then I guess my proposal helps with that? It would be shorter than ever to memoize a method. def settings ||= Settings.new(self) ---------------------------------------- Feature #20202: Memoized endless method definitions https://bugs.ruby-lang.org/issues/20202#change-106390 * Author: matheusrich (Matheus Richard) * Status: Open * Priority: Normal ---------------------------------------- I propose introducing a shorthand for memoized endless method definitions: ```rb class Foo def bar ||= :memoized_value # It should behave like def bar = (@bar ||= :memoized_value) end ``` Not only is this shorter and (IMO) a natural follow-up for endless method definitions, but it's also a common pattern on Ruby codebases. It's very useful to decompose responsibilities into several objects: ```rb class User def notifications_enabled? = settings.notifications? def enable_notifications = (settings.notifications = true) def disable_notifications = (settings.notifications = false) private def settings = @settings ||= Settings.new(self) end class User::Settings attr_writer :notifications def initialize(user) @user = user @notifications = false end def notifications? = @notifications end u = User.new u.notifications_enabled? # => false u.enable_notifications u.notifications_enabled? # => true ``` In the example, the `settings` method could be rewritten as ```rb def settings ||= Settings.new(self) ``` -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/