No named parameters in Ruby? -
this simple can't believe caught me.
def meth(id, options = "options", scope = "scope") puts options end meth(1, scope = "meh") -> "meh"
i tend use hashes argument options because how herd did it– , quite clean. thought standard. today, after 3 hours of bug hunting, traced down error gem happen using assumes named parameters honored. not.
so, question this: named parameter officially not honored in ruby (1.9.3), or side effect of i'm missing? if not, why not?
what's happening:
# assign value of "meh" scope, outside meth , equivalent # scope = "meth" # meth(1, scope) meth(1, scope = "meh") # ruby takes return value of assignment scope, "meh" # if run `puts scope` @ point "meh" meth(1, "meh") # id = 1, options = "meh", scope = "scope" puts options # => "meh"
there no support* named parameters (see below 2.0 update). you're seeing result of assigning "meh"
scope
being passed options
value in meth
. value of assignment, of course, "meh"
.
there several ways of doing it:
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, setting instance variables opts.each |key, value| instance_variable_set "@#{key}", value # or, if have setter methods send "#{key}=", value end @options ||= "options" @scope ||= "scope" end # can call either of these: meth 1, :scope => "meh" meth 1, scope: "meh"
and on. they're workarounds, though, lack of named parameters.
edit (february 15, 2013):
* well, at least until upcoming ruby 2.0, supports keyword arguments! of writing it's on release candidate 2, last before official release. although you'll need know methods above work 1.8.7, 1.9.3, etc., able work newer versions have following option:
def meth(id, options: "options", scope: "scope") puts options end meth 1, scope: "meh" # => "options"
Comments
Post a Comment