Cary Swoveland
Cary Swoveland

Reputation: 110675

Would the introduction of a keyword "singleton_class" break Ruby code or cause other difficulties?

Suppose one wished to create a class having a class instance variable, a getter for that variable, a class method and an instance method. One might write the following.

class C
  @v = 1

  def hi
    'hi'
  end

  class << self
    attr_reader :v

    def ho
      'ho'
    end
  end
end

C.methods(false)
  #=> [:v, :ho]
C.ho
  #=> "ho" 
C.v
  #=> 1

This could be written many other ways, of course. For example:

class C
  @v = 1

  def hi
    'hi'
  end

  def self.ho
    'ho'
  end

  singleton_class.class_eval do
    attr_reader :v
  end
end

C.methods(false)
  #=> [:v, :ho]
C.ho
  #=> "ho" 
C.v
  #=> 1

In both cases, class << self and singleton_class.class_eval cause self to change from C to C.singleton_class. Suppose there were a keyword singleton_class that did the same thing, allowing us to write the following.

class C
  @v = 1

  def hi
    'hi'
  end

  singleton_class 

  attr_reader :v

  def ho
    'ho'
  end
end

C.methods(false)
  #=> [:v, :ho]
C.ho
  #=> "ho" 
C.v
  #=> 1

One could have another keyword that would permit self to flip back and forth between C and its singleton class, but it might be simplest to require everything after singleton_class to be related to the singleton class.

It would not seem that conflicts would arise between the use of the keyword singleton_class and local variables or methods of the same name. Consider, for example, the use of the keyword private: (After writing the following I learned that my long-standing belief that private is a keyword was incorrect; it is the method Module#private used without an argument. I am leaving this here as it is referenced in the comments.)

class C
  def m
    private = 'hi'
    private
  end
  private :m

  private
  def private
    'ho'
  end
end
c = C.new
c.m
  #=> NoMethodError (private method `m' called...
c.send :m
  #=> "hi"
c.private
  #=> NoMethodError (private method `private' called...
c.send :private
  #=> "ho"

My question is given in the title. Feel free to also offer an opinion as to whether Ruby would benefit from the introduction of a keyword to be used in this way.

Upvotes: 2

Views: 77

Answers (1)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369438

Yes. Introducing a new keyword always breaks existing code.

Before, whatever you introduce was a valid identifier, now it is not.

That is why keywords are very "expensive" and should be used very sparingly. (Ruby already has way too many of them, IMO).

Upvotes: 1

Related Questions