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.

【初歩中の初歩】Ruby・if文を三項演算子でスマートに書いてみよう

Last updated at Posted at 2021-09-12

今回はタイトルの通り、三項演算子について触れてみます。

文字列aとbが与えられていて、ふたつが一致すれば「Yes」、一致していなければ「No」と表示させるコードを考えてみます。
if文を使う場合のコードが下記のようになります。

if文利用
a = gets
b = gets

if a==b
    print "Yes"
else
    print "No"
end

次に三項演算子を用いて書いた場合が下記になります。

三項演算子利用
a = gets
b = gets

print a==b ? "Yes":"No"

「条件 ? 出力パターン1 : 出力パターン2」でif文がスマートに書けました!

ぜひ使ってみましょう★

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?