0

I wrote the following code

a = [2,4,6]

def add_value_and_index(anArray)
newArray = []
anArray.each_with_index do |element, index|
    total = element + index
    total
    newArray <<"#{total}"
    newArray
  end
  newArray
  #newArray.to_i does not work
end

add_value_and_index(a)

This should return an array which is a combination of the index number and the value. The method works. I however get an output in strings => ["3","5"...] while I want it in integers => [1,2,3].

I tried to add newArray.to_i but this does not work. Any thoughts on how I can turn this array into integers?

2 Answers2

6
newArray <<"#{total}" # WRONG

You're pushing strings into the array with the expectation of getting integers in the end. Change the above line to:

newArray << total

And just FYI, you can use map to clean things up here.

def your_method(array)
  array.map.with_index do |element, index|
    element + index
  end
end
SHS
  • 7,651
  • 3
  • 18
  • 28
  • `each_with_index.map { |element,index| ... }` not `map.with_index` – Filip Bartuzi Dec 22 '14 at 17:40
  • @FilipBartuzi, note where [Enumerator#with_index](http://www.ruby-doc.org/core-2.1.1/Enumerator.html#method-i-with_index) is defined. One nice thing about that method is that it takes a parameter (default `0`) that is the initial index. – Cary Swoveland Dec 23 '14 at 04:05
0

well the error is newArray << total as @humza pointed out.
"#{total}" is string interpolation which is basically evaluating the placeholders within a string.

This is just a one line solution...if you are interested...

a.collect.each_with_index {|num, index| num + index}

also there is no difference between map and collect...
Difference between map and collect in Ruby?

Community
  • 1
  • 1
Aditya Shedge
  • 386
  • 1
  • 7