What is the meaning of "x ... n" in Ruby?

I'm just curious.

Are the rents of both code snippets below doing the same thing? Why does someone want to use ... instead of .. , could .. 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 don't understand why I would like to go from 1 to (n-1) instead of 1 to n

+4
source share
3 answers

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

This is not 1 to n vs. 1 to (n - 1) , it 1 <= x <= n vs. 1 <= x < m .

+10
source

Sometimes an index in some data structure goes from 0 to struct.size () - 1. Then it is useful to have a way to say the following:

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

will print 'a' , 'b' , 'c' . You use the form .. , it prints an extra nil .

+5
source

If you use n - 1 , then if n is 0, you will have n - 1 -1, which is used to indicate the end of the array.

 array[0...0] # Returns no elements array[0..-1] # Returns all elements 
0
source

Source: https://habr.com/ru/post/1336252/


All Articles