Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Ranges
3.
Purpose of Ranges
4.
Testing Membership in a Range
5.
Definition of Membership
6.
Frequently Asked Questions
6.1.
What is a range in Ruby?
6.2.
What is the use of Range in Ruby?
6.3.
What is a nested hash?
6.4.
What are a truthy value and falsy value?
6.5.
In Ruby, what does "!= nil" mean?
7.
Conclusion
Last Updated: Mar 27, 2024

Ranges in Ruby

Author Komal Shaw
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Ruby is the interpreted high-level programming language that supports various programming paradigms. It was designed with an emphasis on programming productivity and simplicity.

A Range object represents the values between a start value and an end value. Two or three dots separate the start and end values in range literals.  Numbers, characters, strings, and objects can be used as range values.

Ranges

A Ruby range represents the set of values with a beginning and an end. Numbers, characters, strings, and objects can be used as range values. It's made with start point..endpoint, start point...endpoint literals, or::new. It allows the code to be more flexible while reducing the code's size. The range is inclusive if two dots are used and the end value is included. The range is exclusive if three dots are used, and the end value is not included:

1..10  			# The integers 1 through 10, including 
10 1.0...10.0  	# The numbers between 1.0 and 10.0, excluding 10.0 itself

Test whether a value is included in a range with the include? method.

cold_war = 1945..1989 
cold_war.include? birthdate.year

 

The concept of ordering is implicit in the definition of a range. There must be some way to compare values to those endpoints if a range is the values between two endpoints. This is accomplished in Ruby using the comparison operator <=>, which compares two operands and returns –1, 0, or 1 depending on their relative order (or equality).

Classes define the <=> operator with an ordering, such as numbers and strings. If a value answers to this operator, it can only be used as a range endpoint.

The range's endpoints and the values "inside" the range is usually of the same class.

However, technically, any value compatible with the range endpoints' <=> operators can be considered a member of the range.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Purpose of Ranges

 

Ranges are mainly used for comparison(primary purpose): determining if a value is within or outside the range. Iteration is an essential secondary purpose: if the class of a range's endpoints specifies a succ method (for successor), there is a distinct set of range members that may be iterated with each, step, and Enumerable methods.

In most Ruby projects, ranges with integer ends are the most popular. Integer ranges can index strings and arrays because they are discrete. They're also a handy technique to represent an enumerable set of ascending values.

Consider the range 'a'..'c', for example: 

r = 'a'..'c' r.each {|l| print "[#{l}]"}
r.step(2) { |l| print "[#{l}]"} 
r.to_a  								# => ['a','b','c']: Enumerable defines to_a

 

Output:

[a][b][c]
[a][c]
['a','b','c']

Testing Membership in a Range

The Range class contains methods for assessing whether or not an arbitrary value belongs to (or is included in) a range. Before delving into these methods more, it's important to note that range membership can be defined in two ways, both related to the distinction between continuous and discrete ranges. A member of the range is a value x of the range begin..end by the first definition if:

begin <= x <= end 

 

And x is a member of the range begin...end (with three dots) if: 

begin <= x < end

Definition of Membership

The first definition of membership works for any Range object and does not require the endpoints to implement the succ function because all range endpoint values must implement the <=> operator. This will be referred to as the continuous membership test.
 

The second definition of membership is discrete membership, dependent on events.

It considers a Range begin..end to be a set, with elements such as begin, begin.succ, begin.succ.succ, and so on.

Range membership is set membership according to this definition, and a value x is only included in a range if it is a value returned by one of the succ invocations. It's worth noting that testing for discrete membership can be a lot more expensive than testing for continuous membership.
 

Include? and member? are two methods available in Ruby 1.8.

In Ruby 1.9, the situation is different. Cover? is a new method in that version of the language that operates similarly to include? and member? in Ruby 1.8: it always utilizes the continuous membership test. In Ruby 1.9, the terms include? and member? are still interchangeable.

These methods, like those in Ruby 1.8, use the continuous membership test if the range's endpoints are numbers. If the endpoints aren't numeric, the discrete membership test is used instead. Most ranges have numeric endpoints in practice, therefore the Range API changes between Ruby 1.8 and 1.9 have little effect.

Frequently Asked Questions

What is a range in Ruby?

A range is a type of object that has a starting and ending value and allows you to design sequences that span the entire range between these two values.

What is the use of Range in Ruby?

Ranges are most commonly used to express a series. Sequences have a beginning, an end, and a method for producing subsequent values in the sequence.

What is a nested hash?

We can use nested hashes to group or associate the data we're working with even more. They assist us in dealing with scenarios in which a category or piece of data is linked to a collection of values rather than a single discrete value.

What are a truthy value and falsy value?

In a boolean context, such as an if statement, it's a value considered True and false, respectively.

In Ruby, what does "!= nil" mean?

Nil is a unique value in Ruby that represents the absence of any value. Nil is a NilClass object. Nothing or void is referred to as nil in Ruby.

Conclusion

In this article, we have extensively discussed Ranges in Ruby, its purpose, and testing membership in a range.

We hope this blog has helped you enhance your knowledge regarding Rangesin Ruby.

If you want to learn more, check out our articles on Ruby Programming LanguageRuby-DocumentationOfficial Ruby FAQ, and Learn Ruby.
 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc.

Enroll in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Coding!

Previous article
Hashes in Ruby
Next article
Symbols in ruby
Live masterclass