Method: PlainText::Util.positive_array_index_checked

Defined in:
lib/plain_text/util.rb

.positive_array_index_checked(index_in, ary, accept_too_big: true, varname: nil) ⇒ Integer

Returns a non-negative Array index for self, performing a check.

Exception is raised if it is out of range.

Wrapper for #positive_array_index

Parameters:

  • index_in (Integer)

    Index to check and convert from. Potentially negative integer.

  • ary (Array)

    Reference Array.

  • accept_too_big: (Boolean, NilClass) (defaults to: true)

    if true (Default), a positive index larger than the last array index is returned as it is. If nil, the last index + 1 is accepted but raises an Exception for anything larger. If false, any index larger than the last index raises an Exception.

  • varname: (NilClass, String) (defaults to: nil)

    Name of the variable (or nil) to be used for error messages.

Returns:

  • (Integer)

    Non-negative index; i.e., if index=-1 is specified for an Array with a size of 3, the returned value is 2 (the last index of it).

Raises:

  • (IndexError)

    if the index is out of the range to negative.



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/plain_text/util.rb', line 63

def positive_array_index_checked(index_in, ary, accept_too_big: true, varname: nil)
  # def self.positive_valid_index_for_array(index_in, ary, varname: nil)
  errmsgs = {}
  %w(of for).each do |i|
    errmsgs[i] = (varname ? "." : sprintf(" %s %s.", i, varname)) 
  end
  
  index = positive_array_index(index_in, ary)  # guaranteed to be Integer or nil
  raise IndexError, sprintf("index (%s) too small for array; minimum: -%d", index_in, ary.size) if !index  # Ruby default Error message (except the variable "index" as opposed to "index_in is used in the true Ruby default).
  if index_in >= 0
    last_index = ary.size - 1
    errnote1 = nil
    if    (index >  last_index + 1) && !accept_too_big
      errnote1 = ' (or +1)'
    elsif (index == last_index + 1) && (false == accept_too_big)
      errnote1 = " "
    end
    raise IndexError, sprintf("Specified index (%s) is larger than the last index (%d)%s%s", index_in, last_index, errnote1, errmsgs['of']) if errnote1
  end
  index
end