Class: Range

Inherits:
Object show all
Defined in:
lib/hotcocoa/core_extensions/range.rb

Overview

HotCocoa extensions to the Range class

Instance Method Summary collapse

Instance Method Details

#to_NSRange(length = nil) ⇒ Object

Deprecated.

MacRuby 0.11+ includes Range#relative_to. This API will be dropped in HotCocoa 0.8.

Create a Cocoa NSRange from a Ruby Range.

Since NSRange does not support negative indexing, you MUST include an argument to this method to indicate the length of the object which the range refers to.

Examples:


(0..10).to_NSRange       # => #<NSRange location=0 length=11>
(1..10).to_NSRange       # => #<NSRange location=1 length=10>
(2..-1).to_NSRange(11)   # => #<NSRange location=2 length=9>
(3..-2).to_NSRange(11)   # => #<NSRange location=3 length=7>
(4...-1).to_NSRange(11)  # => #<NSRange location=4 length=6>
(-3...-1).to_NSRange(11) # => #<NSRange location=8 length=2>
(-5..-1).to_NSRange(11)  # => #<NSRange location=6 length=5>

Parameters:

  • length (Number) (defaults to: nil)

    the length of the object which the range represents



27
28
29
30
31
32
33
34
# File 'lib/hotcocoa/core_extensions/range.rb', line 27

def to_NSRange length = nil
  if (first.negative? or last.negative?) and !length
    raise ArgumentError, 'arg required if range has negative indicies'
  end
  start = (first.negative? ? length + first : first)
  run   = (last.negative?  ? length + last  : last ) - start + (exclude_end? ? 0 : 1)
  NSRange.new start, run
end