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

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

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

相关标签:
4条回答
  • 2021-01-17 07:56

    if you are in Rails, you can convert 1 to 1st, 2 to 2nd, and so on, using ordinalize.

    Example:

    1.ordinalize # => "1st"
    2.ordinalize # => "2nd"
    3.ordinalize # => "3rd"
    ...
    9.ordinalize # => "9th"
    ...
    1000.ordinalize # => "1000th"
    

    And if you want commas in large numbers:

    number_with_delimiter(1000, :delimiter => ',') + 1000.ordinal # => "1,000th"
    

    in ruby you do not have this method but you can add your own in Integer class like this.

    class Integer
      def ordinalize
        case self%10
        when 1
          return "#{self}st"
        when 2
          return "#{self}nd"
        when 3
          return "#{self}rd"
        else
          return "#{self}th"
        end
      end
    end
    
    
    22.ordinalize #=> "22nd"
    
    0 讨论(0)
  • 2021-01-17 08:12

    Using humanize gem, is probably the easiest way. But, yes, it is not built in, however it has only one dependency, so I think its a pretty good choice..

    require 'humanize'
    
    2.humanize  => "two"
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2021-01-17 08:18

    How about Linguistics? Its not built in though. If you want built in , you have to set it up using hashes etc.. See here also for examples

    0 讨论(0)
提交回复
热议问题