Bug #14374
closed
`for` does not splat elements
Added by nobu (Nobuyoshi Nakada) almost 7 years ago.
Updated almost 6 years ago.
Description
In general, it is said that for
statement and each
method call are similar, except for the scope of loop variables.
I found another difference, since 1.9.
a = [Struct.new(:to_ary).new([1, 2])]
a.each {|i, j| p [i, j]} #=> [1, 2]
for i, j in a; p [i, j]; end #=> [#<struct to_ary=[1, 2]>, nil]
In 1.8, the latter result equals the former.
Is this intentional?
- Status changed from Open to Closed
Applied in changeset trunk|r62073.
compile.c: try to convert in massign for
- compile.c (compile_for_masgn): try to convert to an Array if an
element of massign for
is not an Array.
[ruby-core:84931] [Bug #14374]
- Backport changed from 2.3: UNKNOWN, 2.4: UNKNOWN, 2.5: UNKNOWN to 2.3: REQUIRED, 2.4: REQUIRED, 2.5: REQUIRED
I found each
does not call Array.try_convert
so only for
is affected by redefinition of that method.
$ ruby -e 'a = [Struct.new(:to_ary).new([1, 2])]; def Array.try_convert(*);raise;end;a.each {|i, j| p [i, j]}; for i, j in a; p [i, j]; end'
[1, 2]
Traceback (most recent call last):
3: from -e:1:in `<main>'
2: from -e:1:in `each'
1: from -e:1:in `block in <main>'
-e:1:in `try_convert': unhandled exception
https://github.com/nobu/ruby/pull/new/feature/expandarray-for-masgn
Also available in: Atom
PDF
Like0
Like0Like0Like0