Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of having "x...n" in Ruby?

Tags:

ruby

I'm just curious.

Arent both of the code snippets below doing the same thing? Why would someone want to use ... instead of .., wouldnt .. be easier to read?

for x in 1...11
     puts x
end

for x in 1..10
 puts x
end

Sorry if this is too subjective, I just dont understand why I would want to go from 1 to (n-1) instead of 1 to n

like image 433
James Avatar asked Dec 06 '22 23:12

James


2 Answers

10.5 is included in 1...11, but not in 1..10.

It's not 1 to n vs. 1 to (n - 1), it's 1 <= x <= n vs. 1 <= x < m.

like image 128
deceze Avatar answered Dec 21 '22 04:12

deceze


Sometimes the index in some data structure goes form 0 to struct.size() - 1. It's helpful then to have a way of saying this:

a = ['a','b','c']
for i in 0 ... a.length
   puts a[i]
end

will print 'a', 'b', 'c'. It you use the .. form it will print an additional nil.

like image 41
Mihai Toader Avatar answered Dec 21 '22 05:12

Mihai Toader