简体   繁体   中英

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

Ruby 中是否有内置方法来支持这一点?

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"

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

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'

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"

if you are not in Rails you could do

def ordinalize(n)
  return "#{n}th" if (11..13).include?(n % 100)

  case n%10
  when 1; "#{n}st"
  when 2; "#{n}nd"
  when 3; "#{n}rd"
  else    "#{n}th"
  end
end

ordinalize 1
=> "1st"
ordinalize 2
=> "2nd"
ordinalize 11
=> "11th"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM