Project

General

Profile

Actions

Feature #20565

open

Relax formal argument at label

Added by nobu (Nobuyoshi Nakada) 6 months ago. Updated 6 months ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:118250]

Description

Just a thought: if def foo(if:) is possible, shouldn't def foo(C:) and def foo($g:) also be possible...?

Updated by Earlopain (Earlopain _) 6 months ago · Edited

I knew you can use keywords as names here but am not quite sure about this. Positional arguments (against my expectations from keyword arguments) don't allow any of these three versions. Should they also work? I think it would be nice if they behave the same for keyword identifiers at least.

While you are able to create local variables that look like keywords with binding.local_variable_set, the same is not true for identifiers that look like constants or globals.

wrong local variable name '$g' for #Binding:0x00007cd6436e88e0
wrong local variable name 'C' for #Binding:0x0000738701442b08

You can however try to pass a keyword that looks like a constant to a function and the error message there will only be that the keyword is unknown. Trying to pass a global keyword is a generic syntax error:

test.rb:5: syntax error, unexpected ':', expecting ')' (SyntaxError)
foo($g: "abc")

Updated by Eregon (Benoit Daloze) 6 months ago · Edited

I think it should remain forbidden, parametes must be local variables, but C and $g are not valid local variable names.

Updated by zverok (Victor Shepelev) 6 months ago

I knew you can use keywords as names here but am not quite sure about this. Positional arguments (against my expectations from keyword arguments) don't allow any of these three versions. Should they also work?

The reason why keywords can be used in names is expressiveness on the caller site (not relevant to positional argument), like

validate :something, if: :something_else
association :name, class: "Blah"

It is inconvenient to fetch such argument values, but it allows to create very expressive APIs.

The alternative would be to have—sometimes discussed—“renaming” declarations in signatures, something like

def validate(name, condition if: nil)

With argument named if: by the caller, but available as a local variable condition in the method body.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0