ruby - How to sort "chapter numbers" like 1.1.1, 1.2.1, 1.2.46, etc.? -


is there quick way sort "chapter numbers" in ruby?

1.1.1 1.1.2 1.2.1 1.3.1 1.3.2 1.3.3 10.42.64 etc.? 

do have write enumerator or that?

in ruby, arrays ordered lexicographically, easiest way convert these arrays , sort them:

chapters = %w[1.1.1 1.1.2 1.2.1 1.3.1 1.3.2 1.3.3 10.42.64]  chapters.sort_by {|chapter| chapter.split('.').map(&:to_i) } # => ["1.1.1", "1.1.2", "1.2.1", "1.3.1", "1.3.2", "1.3.3", "10.42.64"] 

of course, real solution use objects instead of slugging around arrays of strings of numbers. after all, ruby object-oriented language, not arrays-of-strings-of-numbers-oriented language:

class chapternumber   include comparable    def initialize(*nums)     self.nums = nums   end    def <=>(other)     nums <=> other.nums   end    def to_s     nums.join('.')   end    alias_method :inspect, :to_s    protected    attr_reader :nums    private    attr_writer :nums end  chapters = [chapternumber.new(1, 1, 1), chapternumber.new(1, 1, 2),    chapternumber.new(1, 2, 1), chapternumber.new(1, 3, 1),    chapternumber.new(1, 3, 2), chapternumber.new(1, 3, 3),    chapternumber.new(10, 42, 64)]  chapters.sort # => [1.1.1, 1.1.2, 1.2.1, 1.3.1, 1.3.2, 1.3.3, 10.42.64] 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -