Class: Range

Inherits:
NSObject show all
Includes:
Enumerable

Overview

A Range represents an interval---a set of values with a start and an end. Ranges may be constructed using the s..e and s...e literals, or with Range::new. Ranges constructed using .. run from the start to the end inclusively. Those created using ... exclude the end value. When used as an iterator, ranges return each value in the sequence.

(-1..-5).to_a      #=> []
(-5..-1).to_a      #=> [-5, -4, -3, -2, -1]
('a'..'e').to_a    #=> ["a", "b", "c", "d", "e"]
('a'...'e').to_a   #=> ["a", "b", "c", "d"]

Ranges can be constructed using objects of any type, as long as the objects can be compared using their operator and they support the succ method to return the next object in sequence.

class Xs                # represent a string of 'x's
  include Comparable
  attr :length
  def initialize(n)
    @length = n
  end
  def succ
    Xs.new(@length + 1)
  end
  def <=>(other)
    @length <=> other.length
  end
  def to_s
    sprintf "%2d #{inspect}", @length
  end
  def inspect
    'x' * @length
  end
end

r = Xs.new(3)..Xs.new(6)   #=> xxx..xxxxxx
r.to_a                     #=> [xxx, xxxx, xxxxx, xxxxxx]
r.member?(Xs.new(5))       #=> true

In the previous code example, class Xs includes the Comparable module. This is because Enumerable#member? checks for equality using ==. Including Comparable ensures that the == method is defined in terms of the method implemented in Xs.

Instance Method Summary (collapse)

Methods included from Enumerable

#_count, #all?, #any?, #collect, #collect_concat, #count, #cycle, #detect, #drop, #drop_while, #each_cons, #each_entry, #each_slice, #each_with_index, #each_with_object, #entries, #find, #find_all, #find_index, #flat_map, #grep, #group_by, #inject, #map, #max_by, #min_by, #minmax, #minmax_by, #none?, #one?, #partition, #reduce, #reject, #reverse_each, #select, #sort, #sort_by, #take, #take_while, #to_a, #zip

Methods inherited from NSObject

#!, #!=, #!~, #, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, alloc, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #dup, #enum_for, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_dup, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version

Constructor Details

- (Range) new(start, end)

Constructs a range using the given start and end. If the third parameter is omitted or is false, the range will include the end object; otherwise, it will be excluded.

Returns:

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class NSObject

Instance Method Details

- (Boolean) ==(obj)

Returns true only if obj is a Range, has equivalent beginning and end items (by comparing them with ==), and has the same exclude_end? setting as rng.

(0..2) == (0..2)            #=> true
(0..2) == Range.new(0,2)    #=> true
(0..2) == (0...2)           #=> false

Returns:

  • (Boolean)

- (Boolean) ===(obj)

Returns true if obj is an element of rng, false otherwise. Conveniently, === is the comparison operator used by case statements.

case 79
when 1..50   then   print "low\n"
when 51..75  then   print "medium\n"
when 76..100 then   print "high\n"
end

produces:

high

Returns:

  • (Boolean)

- (Object) begin

Returns the first object in rng.

Returns:

- (Boolean) cover?(val)

Returns true if obj is between beg and end, i.e beg

("a".."z").cover?("c")    #=> true
("a".."z").cover?("5")    #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Range) each {|i| ... } - (Enumerator) each

Iterates over the elements rng, passing each in turn to the block. You can only iterate if the start object of the range supports the succ method (which means that you can't iterate over ranges of Float objects).

If no block is given, an enumerator is returned instead.

(10..15).each do |n|
   print n, ' '
end

produces:

10 11 12 13 14 15

Overloads:

  • - each {|i| ... }

    Yields:

    • (i)

    Returns:

  • - each

    Returns:

- (Object) end

Returns the object that defines the end of rng.

(1..10).end    #=> 10
(1...10).end   #=> 10

Returns:

- (Boolean) eql?(obj)

Returns true only if obj is a Range, has equivalent beginning and end items (by comparing them with #eql?), and has the same #exclude_end? setting as rng.

(0..2).eql?(0..2)            #=> true
(0..2).eql?(Range.new(0,2))  #=> true
(0..2).eql?(0...2)           #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Boolean) exclude_end?

Returns true if rng excludes its end value.

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Object) first - (Array) first(n)

Returns the first object in rng, or the first n elements.

Overloads:

- (Fixnum) hash

Generate a hash value such that two ranges with the same start and end points, and the same value for the "exclude end" flag, generate the same hash value.

Returns:

- (Boolean) member?(val) - (Boolean) include?(val)

Returns true if obj is an element of rng, false otherwise. If beg and end are numeric, comparison is done according magnitude of values.

("a".."z").include?("g")  # -> true
("a".."z").include?("A")  # -> false

Overloads:

  • - member?

    Returns:

    • (Boolean)
  • - include?

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

- (Object) initialize_copy

- (String) inspect

Convert this range object to a printable form (using inspect to convert the start and end objects).

Returns:

- (Object) last - (Array) last(n)

Returns the last object in rng, or the last n elements.

Overloads:

- (Object) max - (Object) max {|a, b| ... }

Returns the maximum value in rng. The second uses the block to compare values. Returns nil if the first value in range is larger than the last value.

Overloads:

  • - max

    Returns:

  • - max {|a, b| ... }

    Yields:

    • (a, b)

    Returns:

- (Boolean) member?(val) - (Boolean) include?(val)

Returns true if obj is an element of rng, false otherwise. If beg and end are numeric, comparison is done according magnitude of values.

("a".."z").include?("g")  # -> true
("a".."z").include?("A")  # -> false

Overloads:

  • - member?

    Returns:

    • (Boolean)
  • - include?

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

- (Object) min - (Object) min {|a, b| ... }

Returns the minimum value in rng. The second uses the block to compare values. Returns nil if the first value in range is larger than the last value.

Overloads:

  • - min

    Returns:

  • - min {|a, b| ... }

    Yields:

    • (a, b)

    Returns:

- (Range) relative_to(max)

Returns a new Range instance which has negative values in rng expanded relative to max.

(1..10).relative_to(10)   #=> (1..10)
(-3..-1).relative_to(10)  #=> (7..9)

Note that this is a MacRuby specific extension.

Returns:

- (Range) step(n = 1) {|obj| ... } - (Enumerator) step(n = 1)

Iterates over rng, passing each nth element to the block. If the range contains numbers, n is added for each iteration. Otherwise step invokes succ to iterate through range elements. The following code uses class Xs, which is defined in the class-level documentation.

If no block is given, an enumerator is returned instead.

range = Xs.new(1)..Xs.new(10)
range.step(2) {|x| puts x}
range.step(3) {|x| puts x}

produces:

 1 x
 3 xxx
 5 xxxxx
 7 xxxxxxx
 9 xxxxxxxxx
 1 x
 4 xxxx
 7 xxxxxxx
10 xxxxxxxxxx

Overloads:

  • - step {|obj| ... }

    Yields:

    • (obj)

    Returns:

  • - step

    Returns:

- (String) to_s

Convert this range object to a printable form.

Returns: