Monday, December 8

Range Class in Ruby

"Range" is an interval with starting and ending values. In ruby ranges can be created either by "literals" or directly through the "Range::new". And of the literals, x..y & x...y. The main difference of the two mentioned literals, inclusion/exclusion of end values in the range.
x..y: includes the end values

(1..5).each do n
puts n, ' '
end


(1...5).each do n
puts n, ' '
end
In the first literal case, values 1, 2, 3, 4, 5 would be printed. Whereas, in the second litereral case 1, 2, 3, 4 only will be printed.

Interestingly methods end/alias would still give the end value of the range. In such case, end_excluded? is apt choice to distinguish.

No comments: