有没有人有一个真实世界的例子,说明Array#transpose会有用吗?我正在努力将功能与可能的应用程序联系起来。
答案 0 :(得分:1)
如果你有一组名字可能会有用。第一个元素可能是名字,第二个元素可能是姓氏。
您可能想要获取名字或姓氏的列表
names = [["John", "Smith"],["Roger", "Jones"]]
您可以致电names.transpose.first
答案 1 :(得分:1)
考虑以下示例:
class Array
def mean
reduce(:+) / length
end
end
locations = [
[41.311000, -96.138319],
[41.311355, -96.130380],
[41.315319, -96.138319],
[41.316093, -96.129994],
[41.317640, -96.124372],
[41.315964, -96.121883],
[41.313128, -96.121968],
[41.313160, -96.125101],
[41.309775, -96.125316]
]
latitudes, longitudes = locations.transpose
puts latitudes.inspect
# => [41.311, 41.311355, 41.315319, 41.316093, ...
puts longitudes.inspect
# => [-96.138319, -96.13038, -96.138319, -96.129994 ...
weighted_center = [latitudes.mean, longitudes.mean]
puts weighted_center.inspect
# => [41.31371488888889, -96.12840577777779]
的反面