LoginSignup
17
13

More than 5 years have passed since last update.

Rubyでさくっと1st, 2nd, 3rd, 4thという文字列を作りたい!

Posted at

小ネタです。

ActiveSupportならもう既に数字から"1st", "2nd"とかの文字列をきれいに作るなにかがあるに違いない。

と思ったらやっぱりありました。ordinalizeメソッド

require 'active_support/core_ext/integer/inflections'


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

# 2桁でもちゃんとやってくれる!
21.ordinalize
# => "21st"

#負の数でもいけちゃいました
-1.ordinalize
# => "-1st"

ちなみに

(1.5).ordinalize
# NoMethodError: undefined method `ordinalize' for 1.5:Float

Floatには定義されてません。そりゃそうか。

あと、

0.ordinalize
# => "0th"

0のときって"0th"なんだ!

17
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
13