Project

General

Profile

Actions

Bug #14374

closed

`for` does not splat elements

Added by nobu (Nobuyoshi Nakada) about 6 years ago. Updated over 5 years ago.

Status:
Closed
Target version:
-
[ruby-core:84931]

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?

Actions #1

Updated by nobu (Nobuyoshi Nakada) about 6 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]
Actions #2

Updated by nagachika (Tomoyuki Chikanaga) about 6 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) over 5 years ago

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

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0