-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathranges.rb
More file actions
37 lines (31 loc) · 1.4 KB
/
Copy pathranges.rb
File metadata and controls
37 lines (31 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Ranges
# Ranges are a way to represent a sequence of values. They can be created using the `..` and `...` operators.
# The `..` operator creates an inclusive range, which includes the end value, while the `...` operator creates an exclusive range, which excludes the end value.
# The output of a range is an object of the `Range` class, which can be converted to an array using the `to_a` method. Ranges can also be used with characters and in various control flow structures.
# Creating ranges
inclusive_range = 1..5 # This range includes 1, 2, 3, 4, and 5
exclusive_range = 1...5 # This range includes 1, 2, 3, and 4 (but not 5)
puts inclusive_range.to_a.inspect # Output: [1, 2, 3, 4, 5]
puts exclusive_range.to_a.inspect # Output: [1, 2, 3, 4]
# Ranges can also be used with characters. For example:
char_range = 'a'..'e' # This range includes 'a', 'b', 'c', 'd', and 'e'
puts char_range.to_a.inspect # Output: ["a", "b", "c", "d", "e"]
# Ranges can be used in various ways, such as in loops or to check if a value falls within a certain range.
number = 3
if (1..5).include?(number)
puts "#{number} is between 1 and 5."
else
puts "#{number} is not between 1 and 5."
end
# Ranges can also be used with the `case` statement to match a value against a range of values.
score = 85
case score
when (90..100)
puts "Excellent"
when (80...90)
puts "Good"
when (70...80)
puts "Fair"
else
puts "Needs Improvement"
end