Would like to exploit the following behaviour in Ruby
ary = Array.new(5) { |i|
[i, j=2*i, k=j+1]
}
p ary #> [[0, 0, 1], [1, 2, 3], [2, 4, 5], [3, 6, 7], [4, 8, 9]]
It works for my purposes, but I couldn't find in the language definition whether this is legal Ruby. Is it? Or is it likely to break in the future?
[Edit] A smaller working example raising the same issue is
i = 1
ary = [i, j=2*i, k=j+1]
p ary #> [1, 2, 3]
But of course this example only has theoretical relevance contrary to the first, which does have practical relevance.
Array
class say about thenew
method? – Doting[i, j=m1(i), m2(i,j)]
is fine for any methodsm1
andm2
. That wouldn't be in the doc forArray::new
because it is fundamental Ruby behavior (that is common to other languages). – Rigsdalerj=
andk=
in the block are pointless, just return the values directly without assigning them to these temporary variables – Munmronew
block evaluation itself that's unclear, but perhaps the evaluation of the sub-array elements. This question has nothing to do withArray#new
at all, but is about the evaluation of the[i, j=2*i, k=j+1]
expression itself. – Doting::[]
in theArray
documentation. It looks like it's equivalent to the question of whether a method call would evaluate it's arguments in order. So doesfoo(a, b, c)
evaluatea
, thenb
, thenc
before callingfoo
? – Doting[i, j=2*i, k=j+1]
is specifically what you're asking about in your question, you should be more explicit. It's not obvious from reading the question – Munmroruby/spec
that uses values of parameter bindings to the left as default argument values for optional positional parameters to the right, but I would have to dig that up, too. – Iberia[i=0,i+1] #=> [0,1]
, but[i+1,i] #=> NameError (undefined local variable or method 'i' for main:Object)
. Is this a specification of the language? I don't know, but I expect that legions of Ruby coders have over many years written millions of lines of code that depend on arguments being evaluated left-to-right. One can debate whether that is good programming practice, but we can agree that a new version of Ruby that does not evaluate arguments left-to-right would cause havoc... – Rigsdalerm1
andm2
when[m1, m2]
evaluated. Ifm1
is evaluated first we obtainm1 #=> v1
and thenm2 #=> v2
, but ifm2
were evaluated firstm2
andm1
may return values different thanv2
andv1
. It might be advantageous to have parallel processing of method arguments baked into the language (as opposed to creating threads). That would require new coding norms, however, so it would effectively be a new language. Putting that aside, if arguments are evaluated sequentially, I see no reason the Ruby monks would deviate from... – Rigsdaler