0

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

it should have been 'array =array.map{|a| a * n}' why should i have a new array??
@Sayuj : hai sayuj !! where you from?? join my chat room chat.stackoverflow.com/rooms/5676/…
@Seane. There are are a lot of reasons to create objects instead of updating them, map is generally preferrable. Check "functional programming" in google.
@Sayuj, your answer is the more Ruby-ish. Nice!
1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.