Ranges in Ruby
Hey, How are you?
In this article, you are going to talk about the Ruby object type for ranges. Now a range is going to typically be a range of numbers. Right, so let's say numbers from 1-10. Well, we could have an array that would contain all of those numbers or we could simply have a range which will say well, here is the starting point and here is the end point. It's from 1-10. Especially if we have something like 1- 1000, it makes a lot more sense to have something that just tells us the start and end point instead of trying to construct an array or something that has all 1000 numbers in it. We can use a range instead. And there are two kinds of ranges.
| Array vs Range |
There is the inclusive range and the exclusive range. And the notation is right there. That's how it works. It's just the first number and then either 2 or 3 dots depending on which one you want to use. Inclusive would be the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. An exclusive range would be 1, 2, 3, 4, 5, 6, 7, 8, 9. It would exclude the last value. So it would be one up to but not including 10. Now when you're programming in Ruby, you'll find that the first one, the inclusive range, is much more common. Why? Because you can see both of the values that are included so that makes it nice and clear what's included in it.
| Inclusive & Exclusive Range |
And it's one less character to type. So that saves us a little bit of typing as well. But if you need to use the exclusive range, it's there and you can use it. You could also just do 1..9, which I would say is probably more common and what I would recommend to you. Let's try them out, see how they work. So I am going to open up IRB and let's start by just trying out that simple inclusive range, 1-10. You see that it returned 1..10 to me. It didn't return all the numbers. It didn't expand it. It kept it as a range. That's actually a range object. x =1..10 x.class is a range.
CHEERS!!!
Maitrey Patel
Maitrey Patel
Comments
Post a Comment