shah khan
shah khan

Reputation: 137

adding an integer to values in an array in ruby

This is my array

arr = [1,2,3,4,5,6,7,8]

I want to write a method in ruby that would add 5 to each value in the array. How can I do the same ?

Please guide.

Upvotes: 0

Views: 963

Answers (2)

mhutter
mhutter

Reputation: 2916

See the Ruby API Documentation for Array

arr.map! {|i| i+5}

Upvotes: 1

tomferon
tomferon

Reputation: 5001

You can use Array#map like this :

arr = [1,2,3,4,5,6,7,8]
arr.map {|n| n+5 }

See http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-map.

EDIT: map will return a new array, if you want to modify this very array, use map! even if I wouldn't recommend it.

Upvotes: 4

Related Questions