0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】nil、空文字、0を1つのコードで判定したい

Posted at

これまで

numberがnil''(空)0を判定したいとき

number.blank? || number.zero?

これから

nil ''(空) 0を1つのコードで判定できる。
nil ''(空)はto_iすると0になる。

number.to_i.zero?
[1] pry(main)> number = ' '
=> " "
[2] pry(main)> number.to_i.zero?
=> true
[3] pry(main)> number = ''
=> ""
[4] pry(main)> number.to_i.zero?
=> true
[5] pry(main)> number = nil
=> nil
[6] pry(main)> number.to_i.zero?
=> true
0
0
4

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?