1

If I would create a new array out of a preexisting one and modify the content using math operators, what would be a good way to do so? When I try with the code below, I receive an error about undefined methods.

ary1 = [1, 2, 3, 4, 5]
ary2 = ary1.each { |i| 
    ary1[i] = ary1[i] * 10
}
p ary1
p ary2

I assume that math operators are not included in the Array class.

3
  • ruby has strange syntax for that, is that a lambda? Or a "proc" as I've heard they're called in ruby? this question likely fits better on StackOverflow as it's technically specific to how to do X in Ruby or moreover "Why doesn't this code work in Ruby" Commented Jan 3, 2013 at 14:17
  • "I assume that math operators are not included in the Array class.". Array has no need for math operators because it's a container of other objects. The objects themselves might have math operators. Array does have "set" operators, but those have a different purpose. Typically we use map and its aliases, or each_with_object or inject to manipulate/coerce the contents of an array. Commented Jan 3, 2013 at 16:41
  • *, +, - are the math operators for Array. This is easily checked by using ri or checking Array class on ruby-doc.org as seen here. The problem was that you were trying to use * on nil not on Array. Commented Jan 4, 2013 at 18:40

1 Answer 1

8

You're looking for the map function (docs):

ary1 = [1, 2, 3, 4, 5]
ary2 = ary1.map {|value| value * 10}

map is generally a great way to produce a new array by transforming a given array. You pass it a block, which is called for each item in the array. The block receives each item - not the index - as an argument, which I've called value. The return values of the block are collected into a new array, which is then returned when the map function completes.

Sign up to request clarification or add additional context in comments.

1 Comment

The interesting thing is that the word 'collected' was used to describe the behavior for map and not surprisingly collect is an alias for map. ary1 = [*(1..5)] ary2 = ary1.collect {|value| value * 10} (Since the edit got rejected...)

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.