newbie question about blocks

J

Jeppe Jakobsen

------=_Part_7884_19909102.1139780987476
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

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

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

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

dblack

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

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 ([email protected])
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
 
D

Daniel Nugent

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!).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,738
Latest member
JinaMacvit

Latest Threads

Top