Are these two Ruby methods with a hash parameter equivalent? If not, why not? -
first version of method:
def method(param1, param2={}) meth_x(param2).meth_y(param1) meth_z #... end
second version of method (notice second param2)...
def method(param1, param2={}) meth_x(param2={}).meth_y(param1) meth_z #... end
i assume these 2 methods equivalent , i'd go first 1 (less typing, less redundancy).
however, i'm curious if these expected behave differently and, if so, why.
in second, set param2
empty hash before giving parameter meth_x
. in method definition param2 = {}
means if parameter omitted, set default empty hash, in meth_x(param2 = {})
means drop original content of param2 , replace empty hash, giving meth_x
.
irb(main):001:0> = {:alma => 2} => {:alma=>2} irb(main):002:0> puts {:alma=>2} => nil irb(main):003:0> puts(a) {:alma=>2} => nil irb(main):004:0> puts(a = {}) {} => nil
Comments
Post a Comment