Henk van der
Henk van der

Reputation: 3

Return an array with integers in stead of strings

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?

Upvotes: 0

Views: 255

Answers (2)

Aditya Shedge
Aditya Shedge

Reputation: 386

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?

Upvotes: 0

SHS
SHS

Reputation: 7744

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

Upvotes: 6

Related Questions