newbie question about blocks

Discussion in 'Ruby' started by Jeppe Jakobsen, Feb 12, 2006.

  1. ------=_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 :(

    --
    "winners never quit, quitters never win"

    ------=_Part_7884_19909102.1139780987476--
    Jeppe Jakobsen, Feb 12, 2006
    #1
    1. Advertising

  2. Jeppe Jakobsen

    Guest

    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 ()
    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
    , Feb 12, 2006
    #2
    1. Advertising

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



    --
    -Dan Nugent
    Daniel Nugent, Feb 12, 2006
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Arjen
    Replies:
    3
    Views:
    430
    Scott Allen
    Feb 27, 2005
  2. Steve Cooper
    Replies:
    2
    Views:
    120
    Kenta MURATA
    Jan 18, 2004
  3. matt
    Replies:
    1
    Views:
    246
    George Ogata
    Aug 6, 2004
  4. Steven Taylor
    Replies:
    9
    Views:
    241
    Brian Candler
    Apr 27, 2009
  5. Derek Michael

    Newbie Question: Blocks and Parameters

    Derek Michael, Dec 15, 2009, in forum: Ruby
    Replies:
    7
    Views:
    108
    Derek Michael
    Dec 19, 2009
Loading...

Share This Page