Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sunaot
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunaot/ed15d61f13406e4352bb to your computer and use it in GitHub Desktop.
Save sunaot/ed15d61f13406e4352bb to your computer and use it in GitHub Desktop.
キーワード引数で引数の委譲や再定義ってどうやるの?って質問したら答えを教えてもらったよ
##
# 知りたかったこと
def foo(a: 1, b: 2, c: 3, d: 4)
p a, b, c, d
end
# 1. bar の引数定義を a~d のキーワード引数として foo へすべて委譲したい
# 2. bar の引数定義を a~d のキーワード引数とさらに e: 5 を追加したい
def bar( ??? )
foo(a: a, b: b)
end
##
# 答え (thx to @shyouhei)
# 1.
def bar(**hash)
foo(**hash)
end
# 2.
def bar(e: 5, **hash)
foo(**hash)
p e
end
# るびまにも ** 引数で受けることでキーワード引数を Hash としてアクセスできるのは紹介されてた><
# via http://magazine.rubyist.net/?0041-200Special-kwarg
def foo(**kwrest)
p kwrest[:if]
end
foo(if: true) #=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment