vhbsouza
vhbsouza

Reputation: 407

How can I map an array in ruby?

I have an array of integers

a = [3, 4, 5, 6]

and I need to POW this numbers, so they can be like this

a 
# => [9, 16, 25, 36]

I'm trying to do this with this piece of code:

a.map!(&:**2)

but Isn't working :(

Can anyone help me?

Upvotes: 0

Views: 86

Answers (4)

Uri Agassi
Uri Agassi

Reputation: 37409

As a matter of rule, you cannot add parameters to methods using the &:sym syntax.

However, if you follow my suggestion here you could do the following:

class Symbol
  def with(*args, &block)
    ->(caller, *rest) { caller.send(self, *rest, *args, &block) }
  end
end

a.map!(&:**.with(2))
# => [9, 16, 25, 36] 

Upvotes: 1

mu is too short
mu is too short

Reputation: 434615

You can use a lambda with & if you so desire:

square = lambda { |x| x**2 }
a.map!(&square)

This sort of thing is pointless busywork with a block so simple but it can be nice if you have a chain of such things and the blocks are more complicated:

ary.select(&some_complicated_criteria)
   .map(&some_mangling_that_takes_more_than_one_line)
   ...

Collecting bits of logic in lambdas so that you can name the steps has its uses.

Upvotes: 3

andars
andars

Reputation: 1404

You can only use the &: shortcut syntax if you are calling a method on the object with no arguments. In this case, you need to pass 2 as an argument to the ** method.

Instead, expand the block to the full syntax

a.map! { |n| n**2 }

Upvotes: 0

hjing
hjing

Reputation: 4982

You should do this

a.map! { |i| i**2 }

Read the docs.

Upvotes: 2

Related Questions