# Attr\_reader as a class method

**URL:** <https://www.ruby-forum.com/t/attr-reader-as-a-class-method/97657>\
**Category:** Ruby\
**Created:** [July 9, 2006, 9:18am UTC](https://www.ruby-forum.com/t/attr-reader-as-a-class-method/97657 "2006-07-09T09:18:43Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pool007](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3bc359/32.png) [@pool007](https://www.ruby-forum.com/u/pool007)\
**Post date:** [July 9, 2006, 9:18am UTC](https://www.ruby-forum.com/t/attr-reader-as-a-class-method/97657/1 "2006-07-09T09:18:43Z")

</div>

Hi list.

I’d like to use attr\_reader to introduce a class method. For example,  
the following is the code I’ve tried.

irb(main):001:0\> class Foo  
irb(main):002:1\> ONE = 1  
irb(main):003:1\> end  
=\> 1  
irb(main):004:0\> class Foo  
irb(main):005:1\> attr\_reader :ONE  
irb(main):006:1\> end  
=\> nil  
irb(main):007:0\> Foo.ONE  
NoMethodError: undefined method `ONE’ for Foo:Class  
from (irb):7  
from :0  
irb(main):008:0\> class Foo  
irb(main):009:1\> class \<\< self  
irb(main):010:2\> attr\_reader :ONE  
irb(main):011:2\> end  
irb(main):012:1\> end  
=\> nil  
irb(main):013:0\> Foo.ONE  
=\> nil  
irb(main):014:0\>

As you can see, I’ve failed. But the following works:

irb(main):014:0\> class Foo  
irb(main):015:1\> def self.ONE  
irb(main):016:2\> return ONE  
irb(main):017:2\> end  
irb(main):018:1\> end  
=\> nil  
irb(main):019:0\> Foo.ONE  
=\> 1  
irb(main):020:0\>

How can I use attr\_reader to introduce a method I’ve written  
right above?

Sincerely,  
Minkoo S.

---

<div class="post-metadata">

**Author:** ![pool007](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3bc359/32.png) [@pool007](https://www.ruby-forum.com/u/pool007)\
**Post date:** [July 9, 2006, 9:28am UTC](https://www.ruby-forum.com/t/attr-reader-as-a-class-method/97657/2 "2006-07-09T09:28:03Z")

</div>

On Jul 9, 2006, at 12:17 AM, Minkoo S. wrote:

> I’d like to use attr\_reader to introduce a class method. For example,  
> the following is the code I’ve tried.
> 
> irb(main):001:0\> class Foo  
> irb(main):002:1\> ONE = 1  
> irb(main):003:1\> end

The example is simply flawed. ONE is a constant and can be accessed  
from outside Foo as Foo.ONE without any extra code. attr\_\* don’t  
provide access to constants, only instance variables (including the  
instance of a class).

---

<div class="post-metadata">

**Author:** ![pool007](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3bc359/32.png) [@pool007](https://www.ruby-forum.com/u/pool007)\
**Post date:** [July 9, 2006, 9:34am UTC](https://www.ruby-forum.com/t/attr-reader-as-a-class-method/97657/3 "2006-07-09T09:34:28Z")

</div>

I’ve made a mistake. I should’ve call Foo::ONE instead of Foo.ONE  
when accessing constants. By doing so, I don’t have to make any  
methods.

Thanks.

Sincerely,  
Minkoo S.
