Brian Adkins
11/4/2007 12:47:00 AM
On Nov 2, 8:27 pm, transf...@gmail.com wrote:
> Lets say I have a method using the not-so-uncommon keyword options
> pattern:
>
> def foo(*args)
> opts = (Hash === args.last ? args.pop : {})
> ...
>
> Now I want to define another method, which is essentially a special
> alias, that places a particular option as the first argument:
>
> def bar(opt, *args)
> foo(*args, :baz => opt) # doesn't work.
> end
>
> Is there no better way to do this than:
>
> def bar(opt, *args)
> opts = (Hash === args.last ? args.pop : {})
> opts[:baz] = opt
> args << opts
> foo(*args)
> end
>
> Boy, it really makes you wish we had keyword arguments built-in to the
> language!!! I forget, will we have those in 1.9? If so how the above
> look then?
How flexible do you need to be with the argument handling? Would
something like the following work?
def foo a, b='default', opts={}
puts "a is #{a}, b is #{b}"
opts.each {|k,v| puts "#{k} => #{v}"}
puts '-'*10
end
def bar opt, a, b='default2', opts={}
foo a, b, opts.merge!({:baz => opt})
end
foo 1
foo 2, 'foo'
foo 3, 'foo', :opt1 => 'one', :opt2 => 'two'
bar 'extra', 4
bar 'extra', 5, 'bar', :opt1 => 'one', :opt2 => 'two'
Brian Adkins