LoginSignup
48
57

More than 5 years have passed since last update.

Rails の便利なメソッド(数値オブジェクト編)

Posted at

Rails の便利な数値オブジェクト拡張まとめ

multiple_of?(number)

オブジェクトが number で割り切れるかを boolean で返す。

0.multiple_of?(0) #=> true
6.multiple_of?(3) #=> true
6.multiple_of?(4) #=> false

to_s(format, options)

to_s が拡張されていて、いろいろなフォーマットで、文字列を返す。
指定できるフォーマットは :phone, :currency, :percentage, :delimited, :rounded, :human, :human_size

# phone
1234567890.to_s(:phone) #=> "123-456-7890"
1234567890.to_s(:phone, area_code: true, extension: 111) #=> "(123) 456-7890 x 111"
1234567890.to_s(:phone, country_code: 81) #=> "+81-123-456-7890"

# currency
12345.to_s(:currency) #=> "12,345円"
12345.to_s(:currency, locale: :us) #=> "$12,345.00"
12345.to_s(:currency, unit: 'えん', delimiter: '_', format: '合計 %n %u') #=> "合計 12_345 えん"

# その他
12345.to_s(:delimited) #=> "12,345"
123.to_s(:percentage) #=> "123.000%"
123.05.to_s(:rounded, precision: 1) #=> "123.1"
1234567.to_s(:human) #=> "1.23 百万"
123.to_s(:human_size) #=> "123バイト"

他にもいろいろオプションがあるので、見てみて下さい!

day, month, year

秒に変換して返す。days の様に複数形にしても OK
second, minute, hour, week, fortnight もある。

1.day #=> 86400
2.months #=> 5184000

from_now と合わせて使うと便利!

Time.zone.now #=> Sun, 08 May 2016 06:20:50 UTC +00:00
1.day.from_now #=> Mon, 09 May 2016 06:20:52 UTC +00:00

現在から◯◯後の日付を取得できる。

ちなみに、ミリ秒にしたい場合は in_milliseconds メソッドが用意されている(1000 倍しているだけ)

1.hour.in_milliseconds #=> 3600000

byte, kilobyte, megabyte

day と同じように byte 数を計算して返す。
exabyte まである。

1.kilobyte #=> 1024
2.kilobytes #=> 2048

ordinalize

序数にして返す。

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

接尾辞だけ返す ordinal もある。

1.ordinal #=> "st"
2.ordinal #=> "nd"

以上が ActiveSupport の core_ext で拡張されているメソッドです!
Rails 5 では、これらに加えて正負を判定する positive?, negative? が追加されていますが、こちらは Ruby 2.3 に標準で入っているメソッドで、ver 2.2 以前の Ruby 用に追加されています。

48
57
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
48
57