Ruby:为什么我的代码错误?

时间:2016-12-01 18:38:07

标签: ruby

尝试将每个数字乘以数组位置,并且它出现错误:

def the_sum(number)
  i = 0 
  number = 0 
  ans = 0 

  while i < 0 
    ans = string[idx] * string.index
    i += idx
  end

  return ans  
end

test =

the_sum([2, 3]) == 3 # (2*0) + (3*1)

the_sum([2, 3, 5]) == 13 # (2*0) + (3*1) + (5*2)

它出来了?

1 个答案:

答案 0 :(得分:1)

这里有一些问题

def the_sum(number)
  i = 0 
  number = 0 # You just cleared your input variable!
  ans = 0 

  while i < 0  # You previously i = 0 so this will never be true
    ans = string[idx] * string.index
    i += idx
  end

  return ans   # Ans is and was always 0
end

可以通过调用您传递的each_with_index上的Array来解决此问题。

def the_array_sum(array)
    ans = 0 

    array.each_with_index do |val, index|
      ans += val * index 
    end

    return ans
end

the_array_sum([2, 3]) == 3
# => true
the_array_sum([2, 3, 5]) == 13
# => true