Module: Matrix::CoercionHelper
Overview
:nodoc:
Class Method Summary collapse
- .check_int(val, count, kind) ⇒ Object
-
.check_range(val, count, kind) ⇒ Object
Returns ‘nil` for non Ranges Checks range validity, return canonical range with 0 <= begin <= end < count.
-
.coerce_to(obj, cls, meth) ⇒ Object
Helper method to coerce a value into a specific class.
- .coerce_to_int(obj) ⇒ Object
- .coerce_to_matrix(obj) ⇒ Object
Class Method Details
.check_int(val, count, kind) ⇒ Object
1704 1705 1706 1707 1708 1709 1710 |
# File 'lib/matrix.rb', line 1704 def self.check_int(val, count, kind) val = CoercionHelper.coerce_to_int(val) if val >= count || val < -count raise IndexError, "given #{kind} #{val} is outside of #{-count}...#{count}" end val end |
.check_range(val, count, kind) ⇒ Object
Returns ‘nil` for non Ranges Checks range validity, return canonical range with 0 <= begin <= end < count
1694 1695 1696 1697 1698 1699 1700 1701 1702 |
# File 'lib/matrix.rb', line 1694 def self.check_range(val, count, kind) canonical = (val.begin + (val.begin < 0 ? count : 0)).. (val.end ? val.end + (val.end < 0 ? count : 0) - (val.exclude_end? ? 1 : 0) : count - 1) unless 0 <= canonical.begin && canonical.begin <= canonical.end && canonical.end < count raise IndexError, "given range #{val} is outside of #{kind} dimensions: 0...#{count}" end canonical end |
.coerce_to(obj, cls, meth) ⇒ Object
Helper method to coerce a value into a specific class. Raises a TypeError if the coercion fails or the returned value is not of the right class. (from Rubinius)
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 |
# File 'lib/matrix.rb', line 1671 def self.coerce_to(obj, cls, meth) # :nodoc: return obj if obj.kind_of?(cls) raise TypeError, "Expected a #{cls} but got a #{obj.class}" unless obj.respond_to? meth begin ret = obj.__send__(meth) rescue Exception => e raise TypeError, "Coercion error: #{obj.inspect}.#{meth} => #{cls} failed:\n" \ "(#{e.})" end raise TypeError, "Coercion error: obj.#{meth} did NOT return a #{cls} (was #{ret.class})" unless ret.kind_of? cls ret end |
.coerce_to_int(obj) ⇒ Object
1684 1685 1686 |
# File 'lib/matrix.rb', line 1684 def self.coerce_to_int(obj) coerce_to(obj, Integer, :to_int) end |
.coerce_to_matrix(obj) ⇒ Object
1688 1689 1690 |
# File 'lib/matrix.rb', line 1688 def self.coerce_to_matrix(obj) coerce_to(obj, Matrix, :to_matrix) end |