LoginSignup
2
1

More than 3 years have passed since last update.

条件分岐 if

Last updated at Posted at 2020-04-08

環境,前提

Ruby 2.5.1
MacOS Mojave Ver.10.14.6

本記事はRubyがインストールされた前提の記事です。
Rubyをインストールしたあと、とにかくRubyをいろいろ触ってみて慣れていくための記事です。お役に立てば幸いです。

ifとは

プログラミンングには必ず登場するif、
「もし●●の時、◯◯を実行する」というような形で
条件が適用されたら処理を実行し、条件に応じて処理を実行するプログラムです。

ifの基本構造

sample.rb
if 条件 then 
    処理   
end

「条件通りなら処理を実行する」そうでない場合は何もしません。
ifにはendがセットなのでend忘れには注意しましょう。if の後の then は省略可能です。

数値を比較する条件分岐

if文で数値を比較します。以下のコードはpower(変数)に100を代入してその値を比較しています。
if 条件部分の「>」は powerが99より大きい場合は条件が真になり処理が行われます。

sample.rb
power = 100

if power > 99

puts "なかなかのパワーだ!!"

end

実行結果は以下のようになります。

Tarminai
なかなかのパワーだ!!
2
1
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
2
1