在Ruby中按字母顺序对数组进行排序,但最后使用大写单词

时间:2015-02-09 15:57:37

标签: ruby arrays sorting

我正在尝试在Ruby中按字母顺序对字符串进行排序。问题是,它将大写单词放在字符串的开头,但我最后想要它们。

我原来的字符串是:["Apple", "banana", "Zebra", "orange"]

我想要的是什么:["banana", "orange", "Apple", "Zebra"]

4 个答案:

答案 0 :(得分:13)

交换案例进行排序:

["Apple", "banana", "Zebra", "orange"].sort_by(&:swapcase)
#=> ["banana", "orange", "Apple", "Zebra"]

答案 1 :(得分:3)

我假设您要对字符串进行排序,但将大写单词移到排序算法的末尾。

如果只有第一个字符大写,则此方法有效:

p ["banana", "Banana","orange", "Apple", ].sort_by{|x| [x[0].upcase==x[0] ? 1:0,x] }   #=> ["banana", "orange", "Apple", "Banana"]
p ["banana", "Banana","orange", "Apple", ].sort                                        #=> ["Apple", "Banana", "banana", "orange"]

答案 2 :(得分:1)

编辑:显然根据Cary Swoveland的说法,这比使用sort_by要快,而且我倾向于相信他,因为sort已经如此优化了。

def new_sort(array)
  cap, non = array.partition {|el|el[0] == el[0].upcase}
  non.sort + cap.sort
end

puts new_sort ["Apple", "banana", "Zebra", "orange"]
# banna
# orange
# Apple
# Zebra

puts new_sort ["THREE", "two", "one",]
# one
# two
# THREE

答案 3 :(得分:1)

另一种方式:

arr = %w{ Apple banana Zebra Camel iPhone waffles Pancakes }
  # => ["Apple", "banana", "Zebra", "Camel", "iPhone", "waffles", "Pancakes"] 

arr.sort.rotate(arr.count { |s| s[/^[A-Z]/] }) 
  # => ["banana", "iPhone", "waffles", "Apple", "Camel", "Pancakes", "Zebra"] 

我们有:

a = arr.sort
  # => ["Apple", "Camel", "Pancakes", "Zebra", "banana", "iPhone", "waffles"]

nbr_capitalized_words = arr.count { |s| s[/^[A-Z]/] }
  #=> 4

a.rotate(nbr_capitalized_words)
  #=> ["banana", "iPhone", "waffles", "Apple", "Camel", "Pancakes", "Zebra"]