Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could someone explain please how the code works

There is some code:

def func
   def func
      1
   end
end

then I try the following in irb:

func
func.func
func

and get the result:

:func
1
1

Could anyone please explain what's going on? I kinda understand the first output but not the latter. Thanks!

like image 792
unnamed_road Avatar asked Jan 01 '23 14:01

unnamed_road


1 Answers

You define a method inside a method in a global scope. Method definition returns a symbol with it's name.

  1. When you call func for the first time, it's redefined, by the inner func. That's why subsequent calls to func return 1.
  2. Method definition returns a symbol and you can call any globally-defined method on the symbol, that's why you can call func.func. Try to define other method and you'll be able to call it on any symbol:
def func
   def func
      1
   end
end
def a
  'a'
end
func.a
# 'a'
:asd.a
# 'a'
like image 148
mrzasa Avatar answered Jan 17 '23 08:01

mrzasa