I want to sort my array:
p1q1
p1q10
p1q2
to this order:
p1q1
p1q2
p1q10
ie: By growing p
integer, then by growing q
integer.
I 开发者_如何学Goam trying with ids.sort { |id| id.to_i }
constructs, but I am probably re-inventing the wheel... what's the most readable/simplest way to perform this sort?
The easiest way I can think of is this:
>> arr.sort_by { |id| id =~ /^p(\d+)q(\d+)$/ ; [$1.to_i, $2.to_i] }
=> ["p1q1", "p1q2", "p1q10"]
This should work with arbitrary depth, not just two levels:
ids.sort_by { |id| id.scan /\d+/ }
I would to something like this:
def p_q_str_to_num(str)
str =~ /p(\d+)q(\d+)/
($1+$2).to_i
end
a = ["p1q1", "p1q10", "p1q2"]
a.sort {|x,y| p_q_str_to_num(x) <=> p_q_str_to_num(y)}
Returns:
["p1q1", "p1q2", "p1q10"]
精彩评论