Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Fun with function definitions

0 views
Skip to first unread message

Anders Höckersten

unread,
Oct 20, 2005, 4:52:59 PM10/20/05
to
Me and a friend realised earlier today that this is actually a legal
Ruby program:
foo(def foo(a=nil)
puts "hello"
end)
foo

The fact that this works seems to be a side effect of Ruby's semantics
rather than an intended feature, but maybe it's actually useful to be
able to do this? I can't think of any (practical) use of it -
suggestions are welcome.

Regards,
Anders

signature.asc

Mike Wilson

unread,
Oct 20, 2005, 8:46:17 PM10/20/05
to

That's pretty interesting. It makes for some interesting recursion too :)

irb(main):021:0> foo(def foo(a=nil)
irb(main):022:2> puts a
irb(main):023:2> a += 1 if not a.nil?
irb(main):024:2> return a
irb(main):025:2> end)
nil
=> nil
irb(main):026:0> foo(foo(foo(foo(foo(foo(1))))))
1
2
3
4
5
6
=> 7


Mike Wilson

unread,
Oct 20, 2005, 8:57:00 PM10/20/05
to
Err nevermind... that's just not unusual at all...


Stefan Holst

unread,
Oct 21, 2005, 6:22:59 AM10/21/05
to

neat. i experimented a bit an found this one:

irb(main):027:0> foo def foo(o); o+'o'; end || foo('f')
=> "foo"

interestingly, 'or' and || are not the same:

irb(main):030:0> nil or 'fo'
=> "fo"
irb(main):031:0> nil || 'fo'
=> "fo"
irb(main):032:0> foo(nil or 'fo')
SyntaxError: compile error
(irb):32: syntax error
foo(nil or 'fo')
^
(irb):32: syntax error
from (irb):32
from (null):0
irb(main):033:0> foo(nil || 'fo')
=> "foo"

'or' works however with an extra parenthesis:

irb(main):034:0> foo((nil or 'fo'))
=> "foo"

and even

irb(main):035:0> foo((nil; 'fo'))
=> "foo"

ry
stefan


0 new messages