Fun with function definitions

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

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

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

···

On 10/20/05, Anders Höckersten <chucky@dtek.chalmers.se> wrote:

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

Anders Höckersten wrote:

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

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

Err nevermind... that's just not unusual at all...