Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><em>Edit: three-years later; the times, they are a-changin'…</em></p> <p><a href="https://stackoverflow.com/a/1269798/154694">Julik's answer</a> is the simplest and best way to tackle the problem these days:</p> <pre><code>class Foo attr_accessor :dead alias_method :dead?, :dead # will pick up the reader method end </code></pre> <p>My answer to the original question follows, for posterity…</p> <hr> <p>The short version:</p> <p>You can't use a question mark in the name of an instance variable.</p> <p>The longer version:</p> <p>Take, for example, <code>attr_accessor :foo</code> — it's <del>simply</del> conceptually a bit of syntactic sugar for the following:</p> <pre><code>def foo @foo end def foo=(newfoo) @foo = newfoo end </code></pre> <p>Furthermore, the question-mark suffix is mostly just a convention to indicate that the return value of a method is a boolean.</p> <p>The best approximation I can make of what you're going for here…</p> <pre><code>class MyClass def initialize @awesome = true end def awesome? @awesome end end </code></pre> <p>In this case, there may be a case to be made for using <code>attr_accessor</code> — after all, it may be explicit that you're working directly with a boolean attribute. Generally, I save the question-mark suffix for when I am implementing a method whose boolean return value is based on slightly more complex conditions than just the value of an attribute.</p> <p>Cheers!</p> <hr> <p><em>Edit, two years later, after a recent comment:</em></p> <ol> <li>Ruby enforces certain naming conventions. <del>Symbols in Ruby can't have question marks. Thus invocations of <code>:my_boolean_attribute?</code> both will fail with a <code>NameError</code>.</del> Edit: not correct, just use the quoted syntax for a symbol, e.g., <code>:"my_attribute?"</code></li> <li>Symbols are immutable, attempting to assign to one will throw a <code>SyntaxError</code>.</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload