Possible bug with handling of default values for a method

I have the following code snippet:

class SomeClass
def meth1( to = ‘default1’, msg = ‘default2’ )

end
end

param1 = nil ## value is nil because of selecting from a nullable db field
param2 = “Some Message”

sc.meth1( param1, param2 )

The to variable is nil inside meth1, it is not getting assigned the default
value. Is this is a bug in how ruby handles default values? Or is there
something I have wrong in my code? Any ideas?

If you pass nil into the first parameter, it will be nil. The defaults only get
used if you dont supply any argument.

sc.meth1(param1) # msg defaults to 'default2’
sc.meth1 # to defaults to ‘default1’, msg defaults to ‘default2’

···

On Thu, Sep 19, 2002 at 07:15:51AM +0900, Berge, Robert wrote:

I have the following code snippet:

classSomeClass
def meth1( to = ‘default1’, msg = ‘default2’ )

end
end

param1 = nil ## value is nil because of selecting from a nullable db field
param2 = “Some Message”

sc.meth1(
param1, param2 )


Alan Chen
Digikata LLC

Ruby doesn’t fill in default values whenever you pass in nil; it fills
in default values whenever you don’t pass in a particular argument,
e.g.:

def foo(a=‘string1’, b=‘string2’)
p a
p b
end

foo(‘foo’, ‘bar’) #=> “foo”
"bar"
foo(‘foo’) #=> “foo”
"string2"
foo(‘foo’, nil) #=> "foo"
nil

If you want Ruby to fill in your default values whenever nil is passed
in, then you can write:

class SomeClass
def meth1(to=nil, msg=nil)
to ||= 'default1’
msg ||= 'default2’
p to
p msg
end
end

param1 = nil
param2 = “Some Message”

sc = SomeClass.new
sc.meth1( param1, param2 ) #=> “default1”
#=> “Some Message”

Hope this helps,

Paul

···

On Thu, Sep 19, 2002 at 07:15:51AM +0900, Berge, Robert wrote:

I have the following code snippet:

class SomeClass
def meth1( to = ‘default1’, msg = ‘default2’ )

end
end

param1 = nil ## value is nil because of selecting from a nullable db field
param2 = “Some Message”

sc.meth1( param1, param2 )

The to variable is nil inside meth1, it is not getting assigned the default
value. Is this is a bug in how ruby handles default values? Or is there
something I have wrong in my code? Any ideas?