Benjamints Benjamints - 3 years ago 77
Ruby Question

Adding the number to the according index it is positioned in

def incrementer(num)
num.map.with_index(1) do |row, index|
if row > 9
row.to_s.reverse.chop.to_i
else
index + row
end
end
end


Hi,

I have a method which adds the number to the according index it is positioned in. However I have two rules:


  1. The index starts at (1)

  2. If the number is a multiple, remove the first integer off the end of it. 12 would become 2 for example.



The problem is I am unsure how to include an 'if' statement inside a block and I believe I am doing it wrong. I know there is a much better way to write this statement but I am finding it hard.

Example:

incrementer([4,6,9,1,3]) => [5,8,2,5,8]

- 9 + 3 (position of 9 in array) = 12
- Only its last digit 2 should be returned

Answer Source

Use map followed by with_index(1), the argument makes the indexing start from 1.

def incrementer(num)
  num.map.with_index(1) do |row, index|
    row = index + row
    if row > 9
      row.digits.first
    else 
      row
    end
  end
end

p incrementer([3,2,4,10])
#=> [4, 4, 7, 4]
p incrementer([4,6,9,1,3]) #=> [5,8,2,5,8]

It may be better to use n%10 in your if-branch.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download