| 1. |
How do you define ranges in ruby? |
|
Answer» Ruby has METHODS which can give you required feature without much of actually implementing it. In the question, the requirement is it prints/defines a range of numbers. So it can to print numbers from 1 to 10, 3 to 10, -3 to 4. In the following example, if you notice “.” is a METHOD which is being applied to an object, say 3. In Ruby, everything is an object and ‘3’ is considered as an object. “10” is a method argument to “.” method. Now when you say “(3..10)” will be a block of code and calling “to_a” method with print an array range from 3 to 10. The way to define a specific range in ruby is as follows. //----START code-------- > (3..10).to_a => [3, 4, 5, 6, 7, 8, 9, 10] > (-3..4).to_a => [-3, -2, -1, 0, 1, 2, 3, 4] //----end code--------Ruby has implementations to list range for alphabets. You can say any alphabet say ‘a’, ‘d’ or ‘g’ are objects. “.” is method IMPLEMENTATION. When you (‘a’..’h’) will give a block of code and calling ‘to_a’ will generate an array of alphabets starting from ‘a’ and ends at ‘h’. Example to provide range for alphabets //----start code-------- > ('a'..'h').to_a => ["a", "B", "c", "d", "e", "f", "g", "h"] > ('s'..'v').to_a => ["s", "t", "u", "v"] //----end code-------- |
|