How to convert 1 to “first”, 2 to “second”, and so on, in Ruby?

后端 未结 4 1324
慢半拍i
慢半拍i 2021-01-17 07:26

Is there a built-in method in Ruby to support this?

4条回答
  •  半阙折子戏
    2021-01-17 08:16

    I wanted an ordinalize method that has "first, second, third" rather than '1st, 2nd, 3rd' - so here's a little snippet that works up to 10 (and falls back to the Rails ordinalize if it can't find it).

    class TextOrdinalize
    
      def initialize(value)
        @value = value
      end
    
      def text_ordinalize
        ordinalize_mapping[@value] || @value.ordinalize
      end
    
      private
    
      def ordinalize_mapping
        [nil, "first", "second", "third", "fourth", "fifth", "sixth", "seventh",
          "eighth", "ninth", "tenth" ]
      end
    
    end
    

    Here's how it works:

    TextOrdinalize.new(1).text_ordinalize #=> 'first'
    TextOrdinalize.new(2).text_ordinalize #=> 'second'
    TextOrdinalize.new(0).text_ordinalize #=> '0st'
    TextOrdinalize.new(100).text_ordinalize #=> '100th'
    

提交回复
热议问题