Mithun Sasidharan
Mithun Sasidharan

Reputation: 20920

Manipulate elements of arrays dynamically without for loop in ruby

I have an array in ruby and i want to change the values of it's elements dynamically depending on a particular attribute. Suppose i have an array,

array = [123,134,145,515]

And i want to manipulate this elements like getting all the elements multiplied by a parameter, how can i get it done without having to do it explicitly each time using for loop?

Upvotes: 0

Views: 845

Answers (2)

Sayuj
Sayuj

Reputation: 7622

Are you looking for this:

array = [123,134,145,515]
n = <any number>

array1 =array.map{|a| a * n}

or

array.map!{|a| a * n} #which modify the array object itself

Upvotes: 2

Mithun Sasidharan
Mithun Sasidharan

Reputation: 20920

For this, you can use something like the collect method in ruby for arrays.

You can write a method which can be called whenever required passing the array and parameter as argument.

For instance you can write a method similar to this ;

array = [123,134,145,515]
parameter_value = 2

Now, depending on the requirement you can define a method like this :

  array.collect {|x| x * parameter_value}

In this case, this would return an array similar to this :

array = [246, 268, 290, 1030]

Upvotes: 1

Related Questions