function/method arguments

2 views
Skip to first unread message

Robert Citek

unread,
Jan 22, 2010, 1:12:48 PM1/22/10
to spec...@googlegroups.com
Does ruby have a way to make function calls or method calls flexible
with its arguments?

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

Ed Howland

unread,
Jan 22, 2010, 6:33:25 PM1/22/10
to spec...@googlegroups.com
The last paramert in a function, before any block parameter can always
be a hash. So you don't need to enclose it with {}

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
>

Ed Howland

unread,
Jan 23, 2010, 1:14:24 PM1/23/10
to spec...@googlegroups.com
Another approach, one that Rails uses a lot. is to use a variable arg list.
Inside the method, check either the type or count of args.
Does this help?

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

Reply all
Reply to author
Forward
0 new messages