ruby 如何按字母顺序排列忽略大小写的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17799871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I alphabetize an array ignoring case?
提问by user2608684
I'm using Chris Pine's Learn to Program and am stumped on his relatively simple challenge to take user input in the form of a list of random words and then alphabetize them in an array. Questions about this challenge have come up before, but I haven't been able to find my specific question on SO, so I'm sorry if it's a duplicate.
我正在使用 Chris Pine 的“学习编程”,并被他相对简单的挑战所困扰,即以随机单词列表的形式获取用户输入,然后将它们按字母顺序排列在数组中。关于这个挑战的问题之前已经出现过,但我一直无法在 SO 上找到我的具体问题,所以如果它是重复的,我很抱歉。
puts "Here's a fun trick. Type as many words as you want (one per line) and
I'll sort them in...ALPHABETICAL ORDER! Hold on to your hats!"
wordlist = Array.new
while (userInput = gets.chomp) != ''
wordlist.push(userInput)
end
puts wordlist.sort
While this does the trick, I'm trying to figure out how to alphabetize the array without case-sensitivity. This is hard to wrap my head around.
I learned about casecmpbut that seems to be a method for comparing a specific string, as opposed to an array of strings.
虽然这样做可以解决问题,但我试图弄清楚如何在不区分大小写的情况下按字母顺序排列数组。这很难理解。我了解到,casecmp但这似乎是一种比较特定字符串的方法,而不是字符串数组。
So far I've been trying things like:
到目前为止,我一直在尝试这样的事情:
wordlist.to_s.downcase.to_a.sort!
which, in addition to looking bad, doesn't work for multiple reasons, including that Ruby 2.0 doesn't allow strings to be converted to arrays.
除了看起来很糟糕之外,由于多种原因而不起作用,包括 Ruby 2.0 不允许将字符串转换为数组。
回答by pguardiario
How about:
怎么样:
wordlist.sort_by { |word| word.downcase }
Or even shorter:
或者更短:
wordlist.sort_by(&:downcase)
回答by Simon Kaczor
In general, sort_by is not efficient for keys that are simple to compute. A more efficient comparison is to use sort with a block and replace the default comparison operator <=> with casecmp
一般来说, sort_by 对于计算简单的键效率不高。更有效的比较是对块使用 sort 并将默认比较运算符 <=> 替换为 casecmp
wordlist.sort { |w1, w2| w1.casecmp(w2) }
For more information about efficiency gains, consult the official Ruby documentation for the sort_by method: http://www.ruby-doc.org/core-2.1.2/Enumerable.html#method-i-sort_by
有关效率提升的更多信息,请参阅 sort_by 方法的官方 Ruby 文档:http://www.ruby-doc.org/core-2.1.2/Enumerable.html#method-i-sort_by
回答by GalacticPlastic
I had the same question at my Ruby coding bootcamp. Here's what worked for me:
我在我的 Ruby 编码训练营中遇到了同样的问题。以下是对我有用的内容:
puts "Type in a sentence."
sentence = gets.chomp.downcase
puts sentence.split(" ").sort

