Ruby - Introduction Range method

Introduction

Range class has an each method of its own:

Demo

('A'..'Z').each { |letter| print letter }

Result

To test if something is included in the set of objects specified by the range.

For example, with your ('A'..'Z') range, you can check to see if R is within the range, using the include? method:

Demo

('A'..'Z').include?('R') 
('A'..'Z').include?('r')

You can use ranges as array indices to select multiple elements at the same time:

Demo

a = [2, 4, 6, 8, 10, 12] 
p a[1..3]

Result

You can use them to set multiple elements at the same time:

Demo

a = [2, 4, 6, 8, 10, 12] 
a[1..3] = ["a", "b", "c"] 
p a

Result

Related Topic