# Closures defined inside a class method

**URL:** <https://www.ruby-forum.com/t/closures-defined-inside-a-class-method/114611>\
**Category:** Ruby\
**Created:** [September 17, 2007, 1:21pm UTC](https://www.ruby-forum.com/t/closures-defined-inside-a-class-method/114611 "2007-09-17T13:21:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![elliterate](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/9de053/32.png) [@elliterate](https://www.ruby-forum.com/u/elliterate)\
**Post date:** [September 17, 2007, 1:21pm UTC](https://www.ruby-forum.com/t/closures-defined-inside-a-class-method/114611/1 "2007-09-17T13:21:53Z")

</div>

This is just weird…

class ClassA  
def self.func1  
def func2  
puts “In func2”  
end  
func2  
end  
end

> ClassA.func1  
> =\> NameError: undefined local variable or method `func2’ for  
> ClassA:Class

I can call other class methods without explicitly referencing the class  
first due to the fact the call is made in class scope, so why can’t I  
define  
a method in class scope without explicitly prefixing it with ‘self’?

Also…

class ClassB  
def self.func1  
def func2  
puts “In func2”  
end  
end  
end

> a = ClassB.new  
> a.func2  
> =\> “In func2”

func2 looks as though it’s defined as a closure inside class scope func1  
(though it isn’t ^^^^), yet I can call it on an instance of the class?

Someone please explain!

---

<div class="post-metadata">

**Author:** ![elliterate](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/9de053/32.png) [@elliterate](https://www.ruby-forum.com/u/elliterate)\
**Post date:** [September 17, 2007, 1:23pm UTC](https://www.ruby-forum.com/t/closures-defined-inside-a-class-method/114611/2 "2007-09-17T13:23:12Z")

</div>

On Fri, Sep 14, 2007 at 12:04:55AM +0900, Ian L. wrote:

> > ClassA.func1  
> > =\> NameError: undefined local variable or method `func2’ for ClassA:Class

I think you want:

class ClassA  
def self.func1  
def self.func2  
puts “In func2”  
end  
func2  
end  
end

In your example you defined an instance method func2, not a singleton  
method func2, so you would need to create an instance in order to call  
the method (it would be just as if the method definition for func2 were  
outside func1).

> func2 looks as though it’s defined as a closure inside class scope func1  
> (though it isn’t ^^^^), yet I can call it on an instance of the class?

It’s not a closure; func2 does not have access to the scope in which it  
was defined.

Paul
