红宝石地图!函数和嵌套数组

EHN*_*ole 1 ruby arrays multidimensional-array

我需要找到每个嵌套元素的第二个和第三个元素之间的距离

nested_array = [[0, 3, 4], [1, 20, 21], [2, 2, 2]]

def pythag_theorem(a, b)
    c = (a * a) + (b * b)
    result = Math.sqrt(c)
    result
end

def find_distance(array)
  t = 0
  while t < array.length
    array[t].map! {|x| pythag_theorem(x[1], x[2])}
  t += 1
  end
array
end

print find_distance(nested_array)
Run Code Online (Sandbox Code Playgroud)

我越来越

[[0.0, 1.4142135623730951, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]]
Run Code Online (Sandbox Code Playgroud)

当我需要

[[0, 5], [1, 29], [2, 2.82842712474619]]
Run Code Online (Sandbox Code Playgroud)

pythag_theorem 有效,但为什么不是 map!为我工作?谢谢。

mae*_*ics 5

a = [[0, 3, 4], [1, 20, 21], [2, 2, 2]]
a.map {|x,y,z| [x, Math.sqrt(y*y + z*z)]}
# => [[0, 5.0], [1, 29.0], [2, 2.82842712474619]]
Run Code Online (Sandbox Code Playgroud)