title: Ruby: how to find out if an object is a singleton
body: <p>The Ruby docs document for <a href="https://ruby-doc.org/core-2.5.3/Object.html#method-i-singleton_class" rel="nofollow noreferrer">Object#singleton_class</a>:</p>
  
  <blockquote>
    <p>Returns the singleton class of <em>obj</em>. This method creates a new
    singleton class if <em>obj</em> does not have one.</p>
  </blockquote>
  
  <p>Hence, (despite some comments) an object does <strong>not always</strong> have a singleton class. In the following I call an object <em>a singleton</em> if this object has a singleton class.</p>
  
  <p>A newly created object does not have a singleton class, and therefore is not a singleton:</p>
  
  <pre><code>a = "string"                     # =&gt; "string"          # not (yet) a singleton
  b = String.new("another one")    # =&gt; "another one"     # not (yet) a singleton
  [a.class, b.class]               # =&gt; [String, String]
  </code></pre>
  
  <p>An object becomes a singleton only after the definition of a singleton method,</p>
  
  <pre><code>def a.greet
    "hello"
  end
  </code></pre>
  
  <p>or after a singleton class is created due to a class variable being defined to the singleton class of the object</p>
  
  <pre><code>class &lt;&lt; b
    @var = 42
  end
  </code></pre>
  
  <p>Unfortunately, in Ruby a call of the <em>class</em> method does not reveal if the object is a singleton because for singletons the method does not return the actual (singleton) class but the class used for creation of the object:</p>
  
  <pre><code>[a.class, b.class]  # =&gt; [String, String]
  </code></pre>
  
  <p>Merely a call to <em>Marshal.dump</em> unveils if the object is actually a singleton:</p>
  
  <pre><code>Marshal.dump(a, $stdout)
  # TypeError: singleton can't be dumped
  
  Marshal.dump(b, $stdout)
  # TypeError: singleton can't be dumped
  </code></pre>
  
  <p>Is there any other, more elegant way to find out if an object is a singleton?</p>