For example, say I have the following function:
def foo(x, y)
puts "#{x} -- #{y}"
end
x and y are positional arguments so that foo(1,2) differs from
foo(2,1). Is there a way to have arguments that are not positional?
For example, so that I can call foo(x=1, y=2) and it would be the same
as calling foo(1,2) and would be the same as calling foo(y=2, x=1)?
A workaround would be to use a hash and a single argument to foo. For example:
def foo(hash)
puts "#{hash["x"]} -- #{hash["y"]}"
end
foo({"x"=>1, "y"=>2})
Although, that wouldn't allow foo(1,2) to work anymore.
This is more of a curiosity question than anything. I suppose the
"real" solution would be to have a single argument that is an object.
Regards,
- Robert
But other than that, bo.
Ed
Ed Howland
http://greenprogrammer.wordpress.com
http://twitter.com/ed_howland
> --
> Post: spec...@googlegroups.com
> Subscribe: spec_wire...@googlegroups.com
> Unsubscribe: spec_wire+...@googlegroups.com
> Website: http://groups.google.com/group/spec_wire
>
def a(*args)
h = args.first
unless h.kind_of? Hash
args[0] - args[1]
else
h[:x] - h[:y]
end
end
irb(main):076:0> a :x=> 2, :y => 4
=> -2
irb(main):077:0> a 3,3
=> 0
Cheere,
Ed