LoginSignup
2
2

More than 5 years have passed since last update.

Rubyのブロックやメソッドの引数の数

Posted at

Proc#arityを使うとブロックに渡される引数の数を調べれる。

def test(&block)
  if block.arity.zero?
    puts 'no arguments'
  else
    puts "#{block.arity} argument(s) passed"
  end
end

test { |a| }
test { |a,b| }
test { || }
test {  }
# =>
# 1 argument(s) passed
# 2 argument(s) passed
# no arguments
# no arguments

なお、Method#arityというのもあり、同様にメソッドの引数の個数を調べれる。

class Test
  def test1(a,b)
  end

  def test2(a,b,c = 1)
  end

  def test3(a,b,c = 1, d = 2)
  end

  def test4(a,b, &blk)
  end

  def test5(a,b, c = 1, d = 2, &blk)
  end
end
t = Test.new
puts t.method(:test1).arity
puts t.method(:test2).arity
puts t.method(:test3).arity
puts t.method(:test4).arity
puts t.method(:test5).arity
# =>
# 2
# -3
# -3
# 2
# -3

なお、どちらも、可変長引数を受け付ける場合、負の整数-(必要とされる引数の数 + 1)を返却する。

2
2
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
2