ruby map !函数和嵌套数组

标签 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)

我得到了

[[0.0, 1.4142135623730951, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]]

当我需要的时候

[[0, 5], [1, 29], [2, 2.82842712474619]]

pythag_theorem 可以,但为什么 map 不行!为我工作?谢谢。

最佳答案

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]]

关于 ruby map !函数和嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9590918/

相关文章:

ruby - 正则表达式只匹配空格

ruby-on-rails - 从 :through Association 查询

arrays - 快速将协议(protocol)数组转换为任何对象

python - 在 Python 中构建多维字典时出现 KeyError

java - 如何将列表的列表(多维列表)转换为数组的数组(多维数组)?

c - 多维数组和寻址

arrays - 这是 Ruby 中 Array.fill 方法的错误吗?

python - 交错行二维 Numpy 数组

c - 我的 returnList[0] 被重写为 @5'

ruby - Rails 单个资源作为两个其他资源的嵌套资源