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

restキーワード引数に文字列キーのHashを含めるとArgumentErrorになる

2
Last updated at Posted at 2016-02-01

Ruby2.0以上で使えるキーワード引数で、マッチしないキーワード引数を**をつけた引数で引き取れるという仕様があるのですが、キーが文字列の場合ArgumentErrorが発生します。キーワード引数の性質からして当たり前といえば当たり前のような気もしますがちょっとハマりました。

Rubyのバージョン

% ruby -v
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin14]

def test(**rest)
  p rest
end

# OK
test(a:1, :b=>2)
=> {:a=>1, :b=>2}

# NG
test(a:1, 'b'=>2)
ArgumentError: wrong number of arguments (1 for 0)
	from (irb):38:in test
	from (irb):64
	from /Users/kamatama41/.rbenv/versions/2.2.3/bin/irb:11:in <main>

# OK
test({a:1, 'b':2})
=> {:a=>1, :b=>2}

# NG
test({a:1, 'b'=>2})
ArgumentError: wrong number of arguments (1 for 0)
	from (irb):38:in test
	from (irb):72
	from /Users/kamatama41/.rbenv/versions/2.2.3/bin/irb:11:in <main>


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