Bug #9593
closed
Keyword arguments default argument assignment behaviour not consistent with optional argument
Added by chendo (Jack Chen) over 10 years ago.
Updated over 10 years ago.
Description
Given the following code:
def var
100
end
def foo(var: var + 1)
puts "var: #{var.inspect}"
end
def bar(var = var + 1)
puts "var: #{var.inspect}"
end
foo(var: 1)
foo rescue p $!
bar(1)
bar
Ruby 2.0.0:
var: 1
var: 101
var: 1
var: 101
Ruby 2.1.1:
var: 1
#<NoMethodError: undefined method `+' for nil:NilClass>
var: 1
var: 101
What appears to be happening is that since 2.1.1, the keyword argument defines var
as a variable before evaluating the default argument. Personally, I prefer 2.0.0 behaviour, but the way 2.1.1 handles default arguments in non keyword arguments is inconsistent.
The behaviors in 2.0 are incorrect both.
- Status changed from Open to Closed
- % Done changed from 0 to 100
Applied in changeset r45272.
parse.y: optional arguments in rhs
- parse.y (f_arg_asgn): define optional arguments as argument
variables in the rhs default expressions.
[ruby-core:61299] [Bug #9593]
- Backport changed from 1.9.3: UNKNOWN, 2.0.0: UNKNOWN, 2.1: UNKNOWN to 1.9.3: REQUIRED, 2.0.0: REQUIRED, 2.1: REQUIRED
Ok! I will fix the code in Rails. Thank you!
Yes, it's a very old bug.
Optional arguments have same semantics as assignments.
Hi,
I think this change should not be backported to stable branch.
I agree about that it is a long standing bug. But it lives too long to change a behavior during stable releases.
I'm going to fill 'DONTNEED' in 'Backport' field if there's no objection.
- Backport changed from 1.9.3: REQUIRED, 2.0.0: REQUIRED, 2.1: REQUIRED to 1.9.3: DONTNEED, 2.0.0: DONTNEED, 2.1: DONTNEED
No objection. I changed Backport field to DONTNEED
.
- Has duplicate Bug #10280: Regression while evaluating default argments of a method added
- Related to Bug #10314: Default argument lookup fails in Ruby 2.2 for circular shadowed variable names added
- Related to Bug #11074: Block with optional parameter of same closure variable name added
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0