LoginSignup
0
0

More than 5 years have passed since last update.

Rubyのクロージャでスイッチとカウンタを作る

Last updated at Posted at 2018-09-16

クロージャでスイッチとカウンターを作ってみる。

スイッチ

status = false

switch = -> { status = !status }

p switch.call # => true
p switch.call # => false
p switch.call # => true

カウンタ

n = 0

counter = -> { n += 1 }

p counter.call # => 1
p counter.call # => 2
p counter.call # => 3

メソッドの中に閉じる

スイッチ

def create_switch
  status = false
  -> { status = !status }
end

switch = create_switch()

p switch.call # => true
p switch.call # => false
p switch.call # => true

カウンタ

def create_counter
  n = 0
  -> { n += 1 }
end

counter = create_counter()

p counter.call # => 1
p counter.call # => 2
p counter.call # => 3

参考にした記事

クロージャとは - Qiita
Rubyでクロージャを使いたい(導入編)- Qiita
Ruby のブロックはクロージャである

変更点

ご指摘を受け構成・内容を変更しています。詳しくはコメントを参照してください。

0
0
2

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