Forum: Ruby Range#to_a, each - why inconsistent?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Ced5fff44ff8929fc974012ea108b284?d=identicon&s=25 vsv (Guest)
on 2006-03-29 09:29
(Received via mailing list)
Could someone explain me, please, why Range with one element is
iterated inconsistently when this element is empty string:

$ irb --simple-prompt
>> ('a'..'a').to_a
=> ["a"]
>> (1..1).to_a
=> [1]
## but:
>> ("".."").to_a
=> []
>>  ("".."").each{|s| puts 'Inside'}
=> ""..""
Why to_a returns empty [] and each block never executed?
Is it bug or feature?
Any reasonable explanation?

703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2006-03-29 10:09
(Received via mailing list)
On 3/29/06, vsv <> wrote:
> >> ("".."").to_a
this looks like a bug to me

as far as I recall the definition of a range,
"" is part of the range ("".."")
I verified with irb and
("".."") === ""
returns true
"" <=> ""  returns 0 as expected,
"".succ => "" which is not quite conclusive for me, but see below
anyway it seems inconsistent that
("".."").to_a.include?("") returns false

("".."") === "" returns true

No I have mimicked the bahvior with

class NilClass
    def succ; nil; end
    def <=>(other); 0; end

Guess what
(nil..nil).to_a returns ??

[nil] as expected

the behavior you described clearly seems to be a bug.

Deux choses sont infinies : l'univers et la bêtise humaine ; en ce qui
concerne l'univers, je n'en ai pas acquis la certitude absolue.

- Albert Einstein
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel Lifson (Guest)
on 2006-03-29 10:11
(Received via mailing list)
I initially thought it was because "".succ == "" which is not correct,
however I created a custom class that returns itself when succ is

class BadSucc
  include Comparable
  attr_accessor :value
  def <=>(other)
    self.value <=> other.value
  def succ

But this did not seem to work
irb(main):002:0> b =
=> #<BadSucc:0x2dc49a8>
irb(main):003:0> b.value = 1
=> 1
irb(main):008:0> (b..b).to_a
=> [#<BadSucc:0x2dc49a8 @value=1>]

So it seems like it might be a bug to me or there is some other reason
why ("".."").to_a returns empty while (b..b).to_a doesn't.

This topic is locked and can not be replied to.