Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?

More than 3 years have passed since last update.

@nikushi

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

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
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
2
Help us understand the problem. What is going on with this article?