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

后端 未结 4 1307
慢半拍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"
    

提交回复
热议问题