Forum: Ruby newbie question about blocks

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
E17632fab00b930ea3b30e1b98f39675?d=identicon&s=25 Jeppe Jakobsen (Guest)
on 2006-02-12 22:50
(Received via mailing list)
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 :(
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2006-02-12 22:54
(Received via mailing list)
Hi --

On Mon, 13 Feb 2006, 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 :(

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

--
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! http://www.manning.com/books/black
70c8da82d09d3866222976ab8978133c?d=identicon&s=25 Daniel Nugent (Guest)
on 2006-02-12 22:56
(Received via mailing list)
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!).
37a3c73ffbf864e4b28f7f2384ee12ce?d=identicon&s=25 Timothy Hunter (tim-hunter)
on 2006-02-12 23:03
(Received via mailing list)
Jeppe Jakobsen wrote:
>
The collect method will produce a new array:

a.collect {|x| x*x}

or, if you want to modify the original array, use collect!
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2006-02-12 23:34
(Received via mailing list)
Hi --

On Mon, 13 Feb 2006, Daniel Nugent wrote:

> 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 :-)


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! http://www.manning.com/books/black
This topic is locked and can not be replied to.