Ruby: Range Class Flashcards
Which construction for a range means INCLUSIVE of the final character?
A) ..
B) …
..
The two dot construction means INCLUSIVE of the final character.
Example:
(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Which construction for a range means EXCLUSIVE of the final character?
A) ..
B) …
…
The three dot construction means EXCLUSIVE of the final character.
Example:
(1…10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
What the .begin method for a range do?
Returns the object that defines the beginning of the range.
How can you return the first element of a range?
example
Using the begin method.
(1..10).begin
=> 1
.min
Finds the minimum of the range.
.max
Find the maximum of the range.
.include?( )
Ask the range if it includes the object passed to it.
.inject
Performs one action on the first two items of the range, then performs the action on the result of those two. Until all parts of range are used.
.reject
Takes a code block. Returns an ARRAY of the part of the range that hasn’t been reject.
digits.reject { |i| i < 5} # => [5, 6, 7, 8, 9]
Using Range as conditions
Ranges can be used as conditional expressions.
while line = gets
puts line if line =~ /start/ .. line =~ /end/
end
Interval Test
===
The case equality operator is used to see whether some value falls within the interval represented by the range.
(1..10) === 5 # => true
(1..10) === 15 # => false
(1..10) === 3.14159 # => true
(‘a’..’j’) === ‘c’ # => true
(‘a’..’j’) === ‘z’ # => false
When is the === operator used most?
It’s called the case equality operator and is used most often with ….case statements.
car_age = gets.to_f # let's assume it's 5.2 case car_age when 0...1 puts "Mmm.. new car smell" when 1...3 puts "Nice and new" when 3...6 puts "Reliable but slightly dinged" when 6...10 puts "Can be a struggle" when 10...30 puts "Clunker" else puts "Vintage gem" end produces:
Reliable but slightly dinged.
NOTE: Exclusive ranges (…) are normally used for case statements.