rails 技術ブログ

rails 技術ブログ

勉強したことをアウトプットしていきます

三項演算子について

例①

@article.state = @article.publishable? ? :published : :publish_wait

↑の書き方は三項演算子というもの。

条件 ? 結果1 : 結果2

これは以下のように書き換えられる。

if 条件
  結果1
else
  結果2
end



つまり、例1は以下と同じ意味

(@article.state = @article.publishable?) ? (:published) : (:publish_wait)

if @article.state = @article.publishable?
  :published 
else
  :publish_wait



※参考にしたサイト

【Ruby・Rails】三項演算子(条件演算子)を使ってif文をスリムに書こう! - Qiita