From: Jan Svitok Date: 2006-08-26T23:42:22+09:00 Subject: Re: Fun with setter functions On 8/26/06, Kevin Olbrich wrote: > I have a setter function in a class that I would like to pass additional > arguments to, so I can do some addtional calculations if required. > > My first crack at this was to do something like... > > .... > def variable=(value, options=nil) > @variable = value > do_something_cool if options == :flag > end > > Here's the only problem, how do you pass the options? > > object.variable = value, :flag > results in > [value, :flag] being passed to the function. > > I see a couple of work arounds. > 1. send works, but is ugly object.send('variable=',value,:flag) > 2. rewrite variable so that it expects an array and just unpack stuff > from the array > > Any other solutions I may have overlooked? Try def variable=(*args) @variable = args.shift do_something_cool if args.shift == :flag end *args will receive array of arguments passed in either case (i.e. both when one and two parameters are passed) The latter args.shift will return nil if there are no more parameters. Another possibility could be using hash parameters, as rails often does: def variable=(value, options ={}) @variable = value do_something_cool if options[:options] == :flag end Call as: variable = value, :options => :flag