Attr_reader as a class method

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.

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).

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs