[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

newbie question about blocks

Jeppe Jakobsen

2/12/2006 9:50:00 PM

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

--
"winners never quit, quitters never win"
3 Answers

dblack

2/12/2006 9:54:00 PM

0

Tim Hunter

2/12/2006 9:54:00 PM

0

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

Daniel Nugent

2/12/2006 9:56:00 PM

0

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 :(
>
> --
> "winners never quit, quitters never win"
>
>


--
-Dan Nugent