简体   繁体   English

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

[英]How do I sort an array alphabetically?

Having trouble with my syntax have tried a few things but still not getting it right.我的语法有问题尝试了一些东西,但仍然没有做对。 What am I not understanding?我不明白什么? Thanks谢谢

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

Why not just change.sort ?为什么不只是change.sort Array#sort without a block defaults to ascending sort, which is the block { |a, b| a <=> b }没有块的Array#sort默认为升序排序,即块{ |a, b| a <=> b } { |a, b| a <=> b } : { |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"]

Note this block needs to account for the two variables you're comparing, unlike the block you wrote in your question.请注意,此块需要考虑您正在比较的两个变量,这与您在问题中编写的块不同。 Including a custom comparator is only necessary if you wish to modify the way elements are sorted, eg if you want to sort in descending order: { |a, b| b <=> a }仅当您希望修改元素的排序方式时才需要包含自定义比较器,例如,如果您希望按降序排序: { |a, b| b <=> a } { |a, b| b <=> a }

If you want to print a text representation of the array, use如果要打印数组的文本表示,请使用

puts sorted

and if you want to sort in place (not create a new arrray) use sort!如果您想就地排序(而不是创建新数组),请使用sort!

coins = ['cents', 'pennies', 'coins', 'dimes', 'pence', 'quarters']硬币 = ['美分','便士','硬币','角钱','便士','四分之一']

coins.sort!硬币排序!

p coins p币

Change your variable name from change to avoid ruby magic更改您的变量名称以避免红宝石魔法

Use sort_by method:使用sort_by方法:

change = ['cents', 'pennies', 'coins', 'dimes', 'pence', 'quarters']
change.sort_by { |change| change }
# => ["cents", "coins", "dimes", "pence", "pennies", "quarters"] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM