Multiple distinct objects: Difference between revisions

added ruby
(→‎{{header|Python}}: Link to other example)
(added ruby)
Line 36:
which is incorrect since <code>Foo()</code> is only evaluated once. A common correct version is:
<code python>[Foo() for i in xrange(n)]</code>
which evaluates <tt>Foo()</tt> <var>n</var> times and collects each result in a list. This last form is also discussed [[Two-dimensional_array_dimensional array (runtime)#Python|here]], on the correct construction of a two dimensional array.
 
=={{header|Ruby}}==
The mistake is often written as:
<code ruby>[Foo.new] * n # here Foo.new can be any expression that returns a new object</code>
which is incorrect since <code>Foo.new</code> is only evaluated once. A common correct version is:
<code python>Array.new(n) { Foo.new }</code>
which evaluates <tt>Foo.new</tt> <var>n</var> times and collects each result in an Array. This last form is also discussed [[Two-dimensional array (runtime)#Ruby|here]], on the correct construction of a two dimensional array.
Anonymous user