Module: AastraXmlApi::ArrayExtension
- Defined in:
- lib/aastra_xml_api/array_extensions.rb
Instance Method Summary collapse
-
#natsort ⇒ Object
Method which sort an array composed of strings with embedded numbers by the ‘natural’ representation of numbers inside a string.
-
#natsort! ⇒ Object
Same as ‘natsort’ but replace in place.
Instance Method Details
#natsort ⇒ Object
Method which sort an array composed of strings with embedded numbers by the ‘natural’ representation of numbers inside a string.
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/aastra_xml_api/array_extensions.rb', line 21 def natsort reg_number = /\d+/ # We call the sort method of the Array class. self.sort do |str1, str2| # We try to find an embedded number a = str1.match(reg_number) b = str2.match(reg_number) # If there is no number if [a,b].include? nil str1 <=> str2 else while true begin # We compare strings before the number. If there # are equal, we will have to compare the numbers if (comp = a.pre_match <=> b.pre_match) == 0 # If the numbers are equal comp = (a[0] == b[0]) ? comp = a[0] + a.post_match <=> b[0] + b.post_match : comp = a[0].to_i <=> b[0].to_i end str1, str2 = a.post_match, b.post_match a = str1.match(reg_number) b = str2.match(reg_number) rescue break end end comp end end end |
#natsort! ⇒ Object
Same as ‘natsort’ but replace in place.
57 58 59 |
# File 'lib/aastra_xml_api/array_extensions.rb', line 57 def natsort! self.replace(natsort) end |