Method: Range#minmax
- Defined in:
- range.c
#minmax ⇒ Array #minmax {|a, b| ... } ⇒ Array
Returns a 2-element array containing the minimum and maximum value in self, either according to comparison method #<=> or a given block.
With no block given, returns the minimum and maximum values, using #<=> for comparison:
(1..4).minmax # => [1, 4]
(1...4).minmax # => [1, 3]
('a'..'d').minmax # => ["a", "d"]
(-4..-1).minmax # => [-4, -1]
With a block given, the block must return an integer:
-
Negative if
ais smaller thanb. -
Zero if
aandbare equal. -
Positive if
ais larger thanb.
The block is called self.size times to compare elements; returns a 2-element Array containing the minimum and maximum values from self, per the block:
(1..4).minmax {|a, b| -(a <=> b) } # => [4, 1]
Returns [nil, nil] if:
-
The begin value of the range is larger than the end value:
(4..1).minmax # => [nil, nil] (4..1).minmax {|a, b| -(a <=> b) } # => [nil, nil] -
The begin value of an exclusive range is equal to the end value:
(1...1).minmax # => [nil, nil] (1...1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
Raises an exception if self is a beginless or an endless range.
Related: Range#min, Range#max.
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 |
# File 'range.c', line 1791
static VALUE
range_minmax(VALUE range)
{
if (rb_block_given_p()) {
return rb_call_super(0, NULL);
}
return rb_assoc_new(
rb_funcall(range, id_min, 0),
rb_funcall(range, id_max, 0)
);
}
|