Ruby: Range Class Flashcards

1
Q

Which construction for a range means INCLUSIVE of the final character?

A) ..
B) …

A

..

The two dot construction means INCLUSIVE of the final character.

Example:
(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which construction for a range means EXCLUSIVE of the final character?

A) ..
B) …

A

The three dot construction means EXCLUSIVE of the final character.

Example:
(1…10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What the .begin method for a range do?

A

Returns the object that defines the beginning of the range.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can you return the first element of a range?

example

A

Using the begin method.

(1..10).begin

=> 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

.min

A

Finds the minimum of the range.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

.max

A

Find the maximum of the range.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

.include?( )

A

Ask the range if it includes the object passed to it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

.inject

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

.reject

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Using Range as conditions

A

Ranges can be used as conditional expressions.

while line = gets
puts line if line =~ /start/ .. line =~ /end/
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Interval Test

A

===

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

When is the === operator used most?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly