LoginSignup
0
0

More than 3 years have passed since last update.

【Ruby】present/blankメソッドと後置if。

Posted at

個人メモです。

if文とpresent?blank?メソッドを使うことで、変数に値がセットされているかどうかで処理を分岐できる。

rubyではifを後ろに書くことができる(後置ifという)。これを使うとシンプルな記述ができる。

present?とblank?

object.present?
objectに値が存在するとtrueを返す。

object.blank?
objectに値がない、または空だとtrueを返す。
値なしになるのは、nil、empty("")の場合。

値なしの場合
irb(main):333:0> x
=> nil

irb(main):333:0> x.present?
=> false

irb(main):334:0> x.blank?
=> true
値ありの場合
irb(main):335:0> test
=> "テスト"

irb(main):336:0> test.present?
=> true
irb(main):337:0> test.blank?
=> false

補足

blank?と似たメソッドでnil?やempty?もある。
検証するオブジェクトと出力の関係は以下。

メソッド nil empty ("")
blank? true true
nil? true false
empty false true
present? false false
値がemptyの場合
irb(main):340:0> z = ""
=> ""
irb(main):341:0> z.empty?
=> true
irb(main):342:0> z.nil?
=> false


後置if

処理の後ろに条件式をかける。従来の記述の改行やendを省略できる。

処理 if 条件式

後置if
def jadge(x)
  "exist" if x.present?
end
通常のif文
def jadge(x)
  if x.present?
    "exist"
  end
end


変数の値有無による条件分岐

blankやpresentを使うことで条件分岐ができる。
後置ifを使えばスッキリ記述できる。

def jadge(x)
  y = "No" if x.blank?
  y = "Exist" if x.present?
  p "回答は #{y} です"
end
0
0
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
0
0