[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: 'Uninitialized' attr_reader at class returning name of class instead of nil
From:       Matthew Kerwin <matthew () kerwin ! net ! au>
Date:       2017-07-27 12:48:44
Message-ID: CACweHNAmb5xX82B4C2bh87Gr0GMRRNqJoC9rhDvHPAteb4tVrw () mail ! gmail ! com
[Download RAW message or body]

On 27 July 2017 at 21:04, Carlo E. Prelz <fluido@fluido.as> wrote:
>         Subject: 'Uninitialized' attr_reader at class returning name of class instead of nil
>         Date: Thu 27 Jul 17 12:54:29PM +0200
>
> Quoting Michael Schwarze (michael@schwarze-web.de):
>
>> Just out of curiosity:
>>
>> ~~~
>> 2.4.0 :001 > class T
>> 2.4.0 :002?>   attr_reader :name
>> 2.4.0 :003?> end
>> 2.4.0 :004 > T.name
>>  => "T"
>> ~~~
>>
>> Why is it that Ruby returns the name of the class instead of nil in
>> this case?
>
> Because with attr_reader you define an instance method, not a class
> method.
>
> If you write
>
> t::new.name
>
> you will get nil (the method is called on the newly created
> object). If you call T.name you invoke the 'name' method on the class
> object (which returns the name of the class).
>
> Carlo
>

And if you really want to define that method, you have options (of course).

```
# Reopen the eigenclass of 'T'
class <<T
  attr_reader :name
end

# .. or nested ..
class T
  class <<self
    attr_reader :name
  end
end
```

I don't actually know what these will break, but there you go.

Within the scope of the reopened eigenclass (aka singleton class)
methods like `attr_reader` and keywords like `alias` and `private`
(and `self`) make sense, and there's no ambiguity about @ivars either.

If you're cool with the weirdness of scopes and bindings, you can also
do this sort of thing:

```
def T.name
  'Dave'
end

class T
  def self.name
    'Fred'
  end
end
```

Cheers
-- 
  Matthew Kerwin
  http://matthew.kerwin.net.au/

Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic