对字母数组进行排序时,sort
或sort_by
方法在Ruby中如何工作?
sort
或sort_by
的情况下如何手动操作?
示例:
irb(main):036:0> array = ['a','e','b','d','c']
=> ["a", "e", "b", "d", "c"]
irb(main):037:0> array.sort
=> ["a", "b", "c", "d", "e"]
答案 0 :(得分:1)
如果没有重复的元素:
arr = ['a','e','b','d','c']
('a'..'z').to_a & arr
#> ["a", "b", "c", "d", "e"]
如果可能存在重复的元素:
arr = ['a','e','c','b','d','e','c']
h = arr.each_with_object(Hash.new(0)) { |s,h| h[s] += 1 }
#=> {"a"=>1, "e"=>2, "c"=>2, "b"=>1, "d"=>1}
(('a'..'z').to_a & arr).flat_map { |s| [s]*h[s] }
#=> ["a", "b", "c", "c", "d", "e", "e"]
注意:
('a'..'z').to_a & arr
与('a'..'z').to_a & arr.uniq
相同。答案 1 :(得分:0)
也许您可以编写自己的算法?
def custom_sort(ary)
start_ = []
end_ = []
loop do
break if ary.size <= 1
a, b = ary.min, ary.max
start_ << ary.delete_at(ary.index(a))
end_ << ary.delete_at(ary.index(b))
end
start_ << ary[0] unless ary.empty?
start_ + end_.reverse
end
ary = ['a','e','b','d','c','a','a']
custom_sort(ary) #=> ["a", "a", "a", "b", "c", "d", "e"]