Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>Range</code> class in Ruby only supports closed and half-open (right-open) ranges. However, you can easily write your own.</p> <p>Here's an example of a half-open range in Ruby:</p> <pre><code>range = 1.0...10.0 range === 1.0 # =&gt; true range === 10.0 # =&gt; false </code></pre> <p>The total line count for the Ruby 1.9 compliant <code>Range</code> class in Rubinius is 238 lines of Ruby code. If you don't need your open range class to support every wrinkle, corner case, special case, idiosyncrasy, backwards-compatibility quirk and so on of the Ruby Language Specification you can get by with a lot less than that.</p> <p>If you really only need to test for inclusion, then something like this should suffice:</p> <pre><code>class OpenRange attr_reader :first, :last def initialize(first, last, exclusion = {}) exclusion = { first: false, last: false }.merge(exclusion) @first, @last, @first_exclusive, @last_exclusive = first, last, exclusion[:first], exclusion[:last] end def first_exclusive?; @first_exclusive end def last_exclusive?; @last_exclusive end def include?(other) case [first_exclusive?, last_exclusive?] when [true, true] first &lt; other &amp;&amp; other &lt; last when [true, false] first &lt; other &amp;&amp; other &lt;= last when [false, true] first &lt;= other &amp;&amp; other &lt; last when [false, false] first &lt;= other &amp;&amp; other &lt;= last end end alias_method :===, :include? def to_s "#{if first_exclusive? then '(' else '[' end}#@first...#@last#{if last_exclusive? then ')' else ']' end}" end alias_method :inspect, :to_s end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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