Range#to_a, each - why inconsistent?

V

vsv

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?

thanks
Sergey
 
R

Robert Dober

------=_Part_654_4189267.1143619743658
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

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 =3D> ["a"]
(1..1).to_a
=3D> [1]
## but:
("".."").to_a =3D> []
("".."").each{|s| puts 'Inside'}
=3D> ""..""
Why to_a returns empty [] and each block never executed?
Is it bug or feature?
Any reasonable explanation?

thanks
Sergey
Sergey
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
("".."") =3D=3D=3D ""
returns true
"" <=3D> "" returns 0 as expected,
"".succ =3D> "" which is not quite conclusive for me, but see below
anyway it seems inconsistent that
("".."").to_a.include?("") returns false

while
("".."") =3D=3D=3D "" returns true

No I have mimicked the bahvior with

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

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

[nil] as expected

the behavior you described clearly seems to be a bug.
Regards
Robert

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

- Albert Einstein

------=_Part_654_4189267.1143619743658--
 
F

Farrel Lifson

I initially thought it was because "".succ =3D=3D "" which is not correct,
however I created a custom class that returns itself when succ is
called:

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

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

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.

Farrel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top