1
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 1 year has passed since last update.

【初心者向け】色んなRubyの修飾子(備忘録)

Posted at

Rubyの修飾子でシンプルなコードを書こう!

Rubyには、条件分岐や繰り返し処理の結果に応じて、ある処理を実行するという場合に、修飾子を使ってコードをシンプルにすることができます。

Rubyの修飾子は、if、unless、while、until、for、next、breakの後に書かれ、行末まで実行する条件が満たされている場合に実行されます。以下は、基本的な構文の例です。

if

puts "成人です" if age >= 20

unless

puts "未成年です" unless age >= 20

while

i += 1 while i < 5

until

i += 1 until i == 5

for

puts i for i in 1..5

next

next if i == 3

break

break if i == 3

ifを使った繰り返し処理

array = [1, 2, 3, 4, 5]
array.each { |i| puts i if i.even? }

unlessを使った条件分岐

puts "Hello" unless false

まとめ

修飾子を使うと、コードをシンプルに書くことができ、読みやすくなります。

また、処理の実行を条件式の前に書くことで、コードの見通しも良くなります。

しかし、修飾子を過剰に使いすぎると、コードが読みにくくなる可能性もあるそうなので使い時が大事そうですね。

Rubyの修飾子について簡単に解説しました!

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