1
2

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 5 years have passed since last update.

三項演算子

Posted at

学習を進めていて、三項演算子の文法がなかなか覚えられなかったので、ノートにまとめておきます。

def show_post
 last_post = posts.last
    if last_post.present?
      last_post.text? ? last_post.text : '画像が投稿されています'
    else
      'まだ投稿はありません'
    end
  end

↓この部分を「三項演算子」という.

last_post.text? ? last_post.text : '画像が投稿されています'

文法は、以下の通り。

条件式 ? trueの時の値 : falseの時の値

上記の文では、

条件式:もしlast_postが存在していたら? trueの時の値:last_post.text falseの時の値:'画像が投稿されています'というテキスト
となっています。
最初の文をifを用いて書き直すとこうなります。

def show_post
    if (last_post = posts.last).present?
      if last_post.text?
       last_post.text
      else
        '画像が投稿されています'
      end
    else
      'まだ投稿はありません。'
    end
end

使いこなすと色々記述が簡単に書けそうですね^^

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?