Bug #9669
closed
Inconsistent SyntaxError in Ruby 2.1 mandatory keyword arguments definition without parentheses.
Added by tejanium (Teja Sophista) over 10 years ago.
Updated over 10 years ago.
Description
Ruby allowed us to define method with arguments without parentheses.
def foo a:, b:
'bar'
end
#=> :foo
def foo a:, b:
puts 'bar'
end
#=> syntax error
That is consistent. In the first example, 'bar'
is interpreted as the default value of b
. In the second example, the expression puts 'bar'
is inappropriate as the default value, hence the error.
It's because of line continuations. It interpreted the code as:
def foo a:, b: 'bar'
# returns `nil`
end
def foo a:, b: puts 'bar' #<< syntax error
end
There are two ways to add parentheses to make it legal:
## CODE | ## INTERPRETED AS
|
def foo a:, b: | def foo a:, b: puts('bar')
puts('bar') | # returns `nil`
end | end
|
def baz(a:, b:) | def foo(a:, b:)
puts 'bar' | puts 'bar'
end | end
I think Ruby should drop the line continuation, and interpret all three code samples like the second case above, even though it might be hard to solve with the current parser.
Or put a semicolon after b:
.
Matthew Kerwin wrote:
I think Ruby should drop the line continuation, and interpret all three code samples like the second case above, even though it might be hard to solve with the current parser.
Do you mean all line continuations?
Nobuyoshi Nakada wrote:
Do you mean all line continuations?
I don't think so; the only one that ever comes up as a gotcha is a final required keyword argument in a function definition.
- Status changed from Open to Closed
- % Done changed from 0 to 100
Applied in changeset r45405.
parse.y: required kwarg without parentheses
- parse.y (lex_state_e, parser_params, f_arglist, parser_yylex):
separate EXPR_LABELARG from EXPR_BEG and let newline significant,
so that required keyword argument can place at the end of
argument list without parentheses. [ruby-core:61658] [Bug #9669]
- Backport changed from 2.0.0: UNKNOWN, 2.1: UNKNOWN to 2.0.0: DONTNEED, 2.1: REQUIRED
- Status changed from Closed to Open
- Status changed from Open to Closed
Applied in changeset r45408.
parse.y: required kwarg without parentheses
- Has duplicate Bug #9722: Failure with multiple keyword arguments added
- Backport changed from 2.0.0: DONTNEED, 2.1: REQUIRED to 2.0.0: DONTNEED, 2.1: DONE
r45405 and r45408 were backported into ruby_2_1
branch at r46005.
- Related to Bug #10279: Syntax error on Hash with symbol syntax and nested expression: 2.1.3 regression added
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0