Bug #14374

`for` does not splat elements

Added by nobu (Nobuyoshi Nakada) over 2 years ago. Updated almost 2 years ago.

Target version:


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 = [[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?


Updated by nobu (Nobuyoshi Nakada) over 2 years ago

  • 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]

Updated by nagachika (Tomoyuki Chikanaga) over 2 years ago

  • Backport changed from 2.3: UNKNOWN, 2.4: UNKNOWN, 2.5: UNKNOWN to 2.3: REQUIRED, 2.4: REQUIRED, 2.5: REQUIRED

Updated by nobu (Nobuyoshi Nakada) almost 2 years ago

I found each does not call Array.try_convert so only for is affected by redefinition of that method.

$ ruby -e 'a = [[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

Also available in: Atom PDF