gpt4 book ai didi

ruby - 如何按字母顺序对数组进行排序?

转载 作者:数据小太阳 更新时间:2023-10-29 07:22:59 26 4
gpt4 key购买 nike

我的语法有问题,尝试了一些方法,但仍然没有正确。我不明白什么?谢谢

change = ['cents', 'pennies', 'coins', 'dimes', 'pence', 'quarters']
change.sort {|anythinghere| a <=> b puts "Ascending #{anythinghere}" }

最佳答案

为什么不只是 change.sortArray#sort没有 block 默认升序排序,也就是 block { |a, b| a <=> b } :

sorted = change.sort # Ascending sort
sorted = change.sort { |a, b| a <=> b } # Same thing!
sorted
# => ["cents", "coins", "dimes", "pence", "pennies", "quarters"]

请注意,与您在问题中编写的 block 不同,此 block 需要考虑您正在比较的两个变量。仅当您希望修改元素的排序方式时才需要包含自定义比较器,例如如果你想按降序排序:{ |a, b| b <=> a }

如果要打印数组的文本表示,请使用

puts sorted

如果你想就地排序(而不是创建一个新的数组)使用sort!

关于ruby - 如何按字母顺序对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29051469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com