実際に何が起こっているのか:
# Assign a value of "meh" to scope, which is OUTSIDE meth and equivalent to
# scope = "meth"
# meth(1, scope)
meth(1, scope = "meh")
# Ruby takes the return value of assignment to scope, which is "meh"
# If you were to run `puts scope` at this point you would get "meh"
meth(1, "meh")
# id = 1, options = "meh", scope = "scope"
puts options
# => "meh"
名前付きパラメーターのサポート*はありません(2.0の更新については以下を参照してください)。表示されているのは、の値として渡されるように割り当てた結果"meh"
です。もちろん、その割り当ての値はです。scope
options
meth
"meh"
それを行うにはいくつかの方法があります。
def meth(id, opts = {})
# Method 1
options = opts[:options] || "options"
scope = opts[:scope] || "scope"
# Method 2
opts = { :options => "options", :scope => "scope" }.merge(opts)
# Method 3, for setting instance variables
opts.each do |key, value|
instance_variable_set "@#{key}", value
# or, if you have setter methods
send "#{key}=", value
end
@options ||= "options"
@scope ||= "scope"
end
# Then you can call it with either of these:
meth 1, :scope => "meh"
meth 1, scope: "meh"
等々。ただし、名前付きパラメーターがないため、これらはすべて回避策です。
編集(2013年2月15日):
*ええと、少なくとも、キーワード引数をサポートする次のRuby 2.0までは!この記事を書いている時点では、公式リリースの最後のリリース候補2にあります。1.8.7、1.9.3などで動作するには、上記の方法を知っている必要がありますが、新しいバージョンで動作できるようになったものには、次のオプションがあります。
def meth(id, options: "options", scope: "scope")
puts options
end
meth 1, scope: "meh"
# => "options"