Ruby: how to sort array of string parsing the content

Here is my problem: I have an array of string which contains data like that:

array = ["{109}{08} OK",
         "{98} Thx",
         "{108}{0.8}{908} aa",
         "{8}{51} lorem ipsum"]

I would like to sort this array scanning "data inside": here the integers in brace. So, the final array should be like that :

array.custom_sort! => ["{8}{51} lorem ipsum",
                       "{98} Thx",
                       "{109}{08} OK",

"{108}{0.8}{908} aa"]

array.sort_by { |v| (v =~ /(\d+)/) && $1.to_i }

alternately

array.sort_by { |v| /(\d+)/.match(v)[1].to_i }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章