0

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.

2 Answers 2

4

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.

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

Comments

1

See the Ruby API Documentation for Array

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.