Newbie question about blocks

Hi, I want to square every element in my array using a block:

a = (1..1000).to_a
a.each {|x| x**2}

But this does not seem to work, it just outputs my array completely
unchanged :frowning:

···

--
"winners never quit, quitters never win"

Hi --

Hi, I want to square every element in my array using a block:

a = (1..1000).to_a
a.each {|x| x**2}

But this does not seem to work, it just outputs my array completely
unchanged :frowning:

What you want is map, rather than each:

   a.map {|x| x**2 }

each just returns the receiver (i.e., the array itself). map returns
a new array, composed of the results obtained by running the block
once for each item.

"collect" is a synonym for map.

David

···

On Mon, 13 Feb 2006, Jeppe Jakobsen wrote:

--
David A. Black (dblack@wobblini.net)
Ruby Power and Light (http://www.rubypowerandlight.com)

"Ruby for Rails" chapters now available
from Manning Early Access Program! Ruby for Rails

The problem you're seeing is that :each doesn't do anything with the
return values of the block.

What you want is :map or :collect (or their destructive forms :map! or
:collect!).

···

On 2/12/06, Jeppe Jakobsen <jeppe88@gmail.com> wrote:

Hi, I want to square every element in my array using a block:

a = (1..1000).to_a
a.each {|x| x**2}

But this does not seem to work, it just outputs my array completely
unchanged :frowning:

--
"winners never quit, quitters never win"

--
-Dan Nugent

Jeppe Jakobsen wrote:

Hi, I want to square every element in my array using a block:

a = (1..1000).to_a
a.each {|x| x**2}

But this does not seem to work, it just outputs my array completely
unchanged :frowning:

--
"winners never quit, quitters never win"

The collect method will produce a new array:

a.collect {|x| x*x}

or, if you want to modify the original array, use collect!

Hi --

···

On Mon, 13 Feb 2006, Daniel Nugent wrote:

On 2/12/06, Jeppe Jakobsen <jeppe88@gmail.com> wrote:

Hi, I want to square every element in my array using a block:

a = (1..1000).to_a
a.each {|x| x**2}

But this does not seem to work, it just outputs my array completely
unchanged :frowning:

The problem you're seeing is that :each doesn't do anything with the
return values of the block.

What you want is :map or :collect (or their destructive forms :map! or
:collect!).

But probably the methods, not the like-named symbols :slight_smile:

David

--
David A. Black (dblack@wobblini.net)
Ruby Power and Light (http://www.rubypowerandlight.com)

"Ruby for Rails" chapters now available
from Manning Early Access Program! Ruby for Rails