我在下面的街区有点失落。
def sort_string(string)
string.split(" ").sort{|a,b| a.length <=> b.length}.join(" ")
end
根据长度(从最小到最大)对数组进行排序。我的困惑来自于代码块中的变量b
。
如果我将字符串"example string here"
拆分为数组然后对其进行排序,[example],[string],[here]
如何传递到块{|a,b| a.length <=> b.length}
?我不明白如何将数组的元素传递到代码中然后进行比较。
答案 0 :(得分:3)
使用sort
时,Ruby将两个对象传递给块。要比较它们,要么使用内置的<=>
方法,要么通过你设计的一些机制来确定一个是否小于(-1
),等于(0
),或大于(1
)另一个。因此,a
是一个而b
是另一个。
默想:
[1, 2, 3, 4].shuffle # => [4, 1, 3, 2]
.sort { |i, j|
[i, j] # => [4, 1], [4, 3], [1, 3], [4, 2], [3, 2], [1, 2]
i <=> j # => 1, 1, -1, 1, 1, -1
}
# => [1, 2, 3, 4]
记住<=>
的作用,并比较每次循环时i <=> j
比较返回的值。
但是当然你通过阅读sort
的文档来了解这一点: