Ruby自定义字符串排序 [英] Ruby custom string sort
问题描述
输入字符串:
1654AaBcDddeeFF
输出字符串:
1456acddeeABDFF
我尝试的代码:
test_array = []
'1654AaBcDddeeFF'.each_byte do |char|
test_array << char
end
test_array.sort.pack('C*')
# => 1456ABDFFacddee
但是我想最后看看大写字母.
But I would like to see the upper case characters at last.
推荐答案
由于@hirolau已经被接受为swapcase
,因此我提供了另一种选择(尽管我更喜欢他的回答). las,@ Stefan发现了一个漏洞,但提出了一个不错的解决方法:
Since @hirolau's already taken swapcase
, I offered an alternative (even though I prefer his answer). Alas, @Stefan identified a flaw, but suggested a nice fix:
str = '1654AaBcDddeeFF'
order_array = [*'0'..'9',*'a'..'z',*'A'..'Z']
str.each_char.sort_by { |c| order_array.index(c) }.join
#=> "1456acdeABDF"
(我只是一个抄写员.)
(I am a mere scribe.)
此方法的一个优点是您可以将其用于其他订购.例如,如果:
One advantage of this approach is that you could use it for other orderings. For example, if:
str = '16?54!AaBcDdde,eFF'
,您还想在开始时将字符'!?'分组,可以这样写:
and you also wanted to group the characters `'!?,' at the beginning, in that order, you could write:
order_array = [*'!?,'.chars,*'0'..'9',*'a'..'z',*'A'..'Z']
str.each_char.sort_by { |c| order_array.index(c) }.join
#=> "!?,1456acdeABDF"
我们可以通过将order_array
转换为哈希来提高效率.对于最后一个示例:
We can make this a bit more efficient by converting order_array
to a hash. For the last example:
order_hash = Hash[order_array.each_with_index.to_a]
然后:
str.each_char.sort_by { |c| order_hash[c] }.join
# => "!?,1456acddeeABDFF"
这篇关于Ruby自定义字符串排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!