From: "hmdne (hmdne -) via ruby-core" Date: 2024-05-20T08:42:04+00:00 Subject: [ruby-core:117939] [Ruby master Feature#20498] Negated method calls Issue #20498 has been updated by hmdne (hmdne -). I saw such a proposal before and I thought of some syntax and implementation, but I didn't submit that in the previous issue: ```ruby class MethodNegator < BasicObject def initialize(obj) @obj = obj end def method_missing(method, ...) @obj.public_send(method, ...) end def respond_to_missing?(include_all = false) @obj.respond_to?(include_all) end end module Kernel def non(sym=nil) if sym proc { |*args,**kwargs,&block| !sym.to_proc.call(*args,**kwargs,&block) } else MethodNegator.new(self) end end end p "".non.empty? # => true p ["", "a", "b"].select(&non(:empty?)) # => ["a", "b"] ``` ---------------------------------------- Feature #20498: Negated method calls https://bugs.ruby-lang.org/issues/20498#change-108354 * Author: MaxLap (Maxime Lapointe) * Status: Open ---------------------------------------- I want to propose the following syntax: `foo.!bar`. I know it's already valid syntax, but please read on for details. When someone write a somewhat long line of code that is negated, the main way I've seen of doing it is: ``` must_create_user = !User.where(somelong: :condition, even_more: "thing").exists? ``` I personally highly dislike it, as I must keep the "not" in the back of my mind as I read the line. When quickly reading a line like this, it's super easy to misread and understand the opposite result. The current ways around this I can think of are: * rename the variable (can be annoying) * Use `unless` (only possible when in a condition; some people, like me, have a hard time grapsping a `unless`) * use a `.!`in the end (`foo.exists?.!`), I've never seen that and it looks ugly to me (this is subjective). * create a new method name with the negated meaning (not always possible) My proposal would look like this: ``` must_create_user = User.where(somelong: :condition, even_more: "thing").!exists? ``` You cannot forget the bang that you saw 15 words ago, it's right there. It also basically reads as English: "user where ... doesn't exists". The main argument against this I can think of is that it's technically already a valid syntax. I believe it's frowned upon to override the bang operator and I'm not aware of places where it is overridden to with also having a parameter. I made a prototype in RubyNext, which you can try here: https://ruby-next.github.io/#gist:0e133bf6f27f2437193dc034d58083dc -- 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/