0
1

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.

自分用rubyメモ ブロック付きメソッドについて

0
Last updated at Posted at 2016-06-16

ブロック変数を渡してメソッドを実行

block_method.rb
def total(from, to)
  total = 0
  from.upto(to) do |i| # from ~ toの間処理を行う
    if block_given? # メソッドにブロックが付いるかどうか
      total += yield(i) # ブロックで処理した値を加算する
    else
      total += i # そのままnumを加算する。
    end
  end
  total
end

p total(1,10) # 1~10をそのまま加算
p total(1,10){|num| num ** 2} # 1~10の2乗を加算
result
55
385
  • yield()は、通常のメソッドの様に複数の値を渡す事も出来る。
  • その場合、以下の様な書き方になる。|*num|等も使用可能。
block_method.rb
# 省略
yield(a,b,c)
# 省略
p total(1,10){|numa,numb,numc| 省略}

yieldを使わない書き方としては以下がある

block_method2.rb
def total2(from, to, &block) # yieldじゃないやり方。&変数の事をProc引数と呼ぶ。引数の一番最後にしか記述できない。
  total = 0
  from.upto(to) do |num|
    if block
      total += block.call(num)  # callメソッドを使うとブロックを呼び出せる
    else
      total += num
    end
  end
  total
end

p total2(1,10){|num| num ** 2}

block = Proc.new do |num|
  num ** 2
end

p total2(1,10,&block) # ブロック変数を渡す事も可能!(使いまわせる!)

まとめ

  • RubyはとことんDRYな書き方が出来るようになっているんだなと感じた。
  • どんどん使い回ししていこう。
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?