试图在Ruby中按字母顺序排列

时间:2017-04-26 21:34:34

标签: ruby

转动此字符串:

"The quick brown fox jumps over the lazy dog"

进入这个字符串:

"abcdefghijklmnopqrstuvwxyz"

这完全适用于Ruby。任何帮助都会很棒。

4 个答案:

答案 0 :(得分:2)

编辑:因为速度并不总是更好

"The quick brown fox jumps over the lazy dog".downcase.chars.uniq.sort.join.strip

答案 1 :(得分:1)

text = "The quick brown fox jumps over the lazy dog"
text.chars.sort.join
 => "        Tabcdeeefghhijklmnoooopqrrstuuvwxyz" 

或不区分大小写:

str.chars.sort(&:casecmp).join

答案 2 :(得分:0)

str = "The quick brown fox jumps over the lazy dog"
str.scan(/[a-z]/).uniq.sort.join #=> "abcdefghijklmnopqrstuvwxyz"

步骤

str.scan(/[a-z]/) #returns all lowercase letters
str.scan(/[a-z]/).uniq #gets rid of duplicates
str.scan(/[a-z]/).uniq.sort #sorts in alphabetical order
str.scan(/[a-z]/).uniq.sort.join #makes a string

或另一种方式:

str.scan(/[a-z]/).sort.join.squeeze #=> "abcdefghijklmnopqrstuvwxyz"

步骤

str.scan(/[a-z]/) #returns all lowercase letters
str.scan(/[a-z]/).sort #sorts in alphabetical order
str.scan(/[a-z]/).sort.join #makes a string
str.scan(/[a-z]/).sort.join.squeeze #gets rid of duplicates

答案 3 :(得分:0)

更快的解决方案很重要,但却显示出优雅:

str, hash = "This is cat", {}
str.each_char { |c| hash[c.downcase] = 1 }
('a'..'z').inject("") { |s, c| hash[c] ? s+c : s }