Results for: "minmax"

Returns a new 2-element Array containing the minimum and maximum values from self, either per method <=> or per a given block:.

When no block is given, each element in self must respond to method <=> with an Integer; returns a new 2-element Array containing the minimum and maximum values from self, per method <=>:

[0, 1, 2].minmax # => [0, 2]

When a block is given, the block must return an Integer; the block is called self.size-1 times to compare elements; returns a new 2-element Array containing the minimum and maximum values from self, per the block:

['0', '00', '000'].minmax {|a, b| a.size <=> b.size } # => ["0", "000"]

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:

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:

Raises an exception if self is a beginless or an endless range.

Related: Range#min, Range#max.

Returns a 2-element array containing the minimum and maximum elements according to a given criterion. The ordering of equal elements is indeterminate and may be unstable.

With no argument and no block, returns the minimum and maximum elements, using the elements’ own method <=> for comparison:

(1..4).minmax                   # => [1, 4]
(-4..-1).minmax                 # => [-4, -1]
%w[d c b a].minmax              # => ["a", "d"]
{foo: 0, bar: 1, baz: 2}.minmax # => [[:bar, 1], [:foo, 0]]
[].minmax                       # => [nil, nil]

With a block given, returns the minimum and maximum elements as determined by the block:

%w[xxx x xxxx xx].minmax {|a, b| a.size <=> b.size } # => ["x", "xxxx"]
h = {foo: 0, bar: 1, baz: 2}
h.minmax {|pair1, pair2| pair1[1] <=> pair2[1] }
# => [[:foo, 0], [:baz, 2]]
[].minmax {|a, b| a <=> b }                          # => [nil, nil]

Related: min, max, minmax_by.

Returns a 2-element array containing the elements for which the block returns minimum and maximum values:

(1..4).minmax_by {|element| -element }
# => [4, 1]
%w[a b c d].minmax_by {|element| -element.ord }
# => ["d", "a"]
{foo: 0, bar: 1, baz: 2}.minmax_by {|key, value| -value }
# => [[:baz, 2], [:foo, 0]]
[].minmax_by {|element| -element }
# => [nil, nil]

Returns an Enumerator if no block is given.

Related: max_by, minmax, min_by.

Sets the minimum and maximum supported protocol versions. See min_version= and max_version=.

No documentation available
No documentation available
No documentation available

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained. Binding objects can be created using Kernel#binding, and are made available to the callback of Kernel#set_trace_func and instances of TracePoint.

These binding objects can be passed as the second argument of the Kernel#eval method, establishing an environment for the evaluation.

class Demo
  def initialize(n)
    @secret = n
  def get_binding

k1 =
b1 = k1.get_binding
k2 =
b2 = k2.get_binding

eval("@secret", b1)   #=> 99
eval("@secret", b2)   #=> -3
eval("@secret")       #=> nil

Binding objects have no class-specific methods.

Raised when attempting to convert special float values (in particular Infinity or NaN) to numerical classes which don’t support them.

Float::INFINITY.to_r   #=> FloatDomainError: Infinity

In concurrent programming, a monitor is an object or module intended to be used safely by more than one thread. The defining characteristic of a monitor is that its methods are executed with mutual exclusion. That is, at each point in time, at most one thread may be executing any of its methods. This mutual exclusion greatly simplifies reasoning about the implementation of monitors compared to reasoning about parallel code that updates a data structure.

You can read more about the general principles on the Wikipedia page for Monitors.


Simple object.extend

require 'monitor.rb'

buf = []
empty_cond = buf.new_cond

# consumer
Thread.start do
  loop do
    buf.synchronize do
      empty_cond.wait_while { buf.empty? }
      print buf.shift

# producer
while line = ARGF.gets
  buf.synchronize do

The consumer thread waits for the producer thread to push a line to buf while buf.empty?. The producer thread (main thread) reads a line from ARGF and pushes it into buf then calls empty_cond.signal to notify the consumer thread of new data.

Simple Class include

require 'monitor'

class SynchronizedArray < Array

  include MonitorMixin

  def initialize(*args)

  alias :old_shift :shift
  alias :old_unshift :unshift

  def shift(n=1)
    self.synchronize do

  def unshift(item)
    self.synchronize do

  # other methods ...

SynchronizedArray implements an Array with synchronized access to items. This Class is implemented as subclass of Array which includes the MonitorMixin module.

mkmf.rb is used by Ruby C extensions to generate a Makefile which will correctly compile and link the C extension to Ruby and a third-party library.

Represents a regular expression literal that contains interpolation that is being used in the predicate of a conditional to implicitly match against the last line read by an IO object.

if /foo #{bar} baz/ then end

Raised when a gem dependencies file specifies a ruby version that does not match the current version.

Mini String IO [Private]

Acts like a StringIO with reduced API, but without having to require that class.

This class is responsible for generating initial code blocks that will then later be expanded.

The biggest concern when guessing code blocks, is accidentally grabbing one that contains only an “end”. In this example:

def dog
  begonn # mispelled `begin`
  puts "bark"

The following lines would be matched (from bottom to top):

1) end

2) puts "bark"

3) begonn
   puts "bark"

At this point it has no where else to expand, and it will yield this inner code as a block

An Integer object represents an integer value.

You can create an Integer object explicitly with:

You can convert certain objects to Integers with:

An attempt to add a singleton method to an instance of this class causes an exception to be raised.

What’s Here

First, what’s elsewhere. Class Integer:

Here, class Integer provides methods for:





No documentation available

A String object has an arbitrary sequence of bytes, typically representing text or binary data. A String object may be created using String::new or as literals.

String objects differ from Symbol objects in that Symbol objects are designed to be used as identifiers, instead of text or data.

You can create a String object explicitly with:

You can convert certain objects to Strings with:

Some String methods modify self. Typically, a method whose name ends with ! modifies self and returns self; often a similarly named method (without the !) returns a new string.

In general, if there exist both bang and non-bang version of method, the bang! mutates and the non-bang! does not. However, a method without a bang can also mutate, such as String#replace.

Substitution Methods

These methods perform substitutions:

Each of these methods takes:

The examples in this section mostly use methods String#sub and String#gsub; the principles illustrated apply to all four substitution methods.

Argument pattern

Argument pattern is commonly a regular expression:

s = 'hello'
s.sub(/[aeiou]/, '*')# => "h*llo"
s.gsub(/[aeiou]/, '*') # => "h*ll*"
s.gsub(/[aeiou]/, '')# => "hll"
s.sub(/ell/, 'al')   # => "halo"
s.gsub(/xyzzy/, '*') # => "hello"
'THX1138'.gsub(/\d+/, '00') # => "THX00"

When pattern is a string, all its characters are treated as ordinary characters (not as regexp special characters):

'THX1138'.gsub('\d+', '00') # => "THX1138"

String replacement

If replacement is a string, that string will determine the replacing string that is to be substituted for the matched text.

Each of the examples above uses a simple string as the replacing string.

String replacement may contain back-references to the pattern’s captures:

See Regexp for details.

Note that within the string replacement, a character combination such as $& is treated as ordinary text, and not as a special match variable. However, you may refer to some special match variables using these combinations:

See Regexp for details.

Note that \\ is interpreted as an escape, i.e., a single backslash.

Note also that a string literal consumes backslashes. See string literal for details about string literals.

A back-reference is typically preceded by an additional backslash. For example, if you want to write a back-reference \& in replacement with a double-quoted string literal, you need to write "..\\&..".

If you want to write a non-back-reference string \& in replacement, you need first to escape the backslash to prevent this method from interpreting it as a back-reference, and then you need to escape the backslashes again to prevent a string literal from consuming them: "..\\\\&..".

You may want to use the block form to avoid a lot of backslashes.

Hash replacement

If argument replacement is a hash, and pattern matches one of its keys, the replacing string is the value for that key:

h = {'foo' => 'bar', 'baz' => 'bat'}
'food'.sub('foo', h) # => "bard"

Note that a symbol key does not match:

h = {foo: 'bar', baz: 'bat'}
'food'.sub('foo', h) # => "d"


In the block form, the current match string is passed to the block; the block’s return value becomes the replacing string:

 s = '@'
'1234'.gsub(/\d/) {|match| s.succ! } # => "ABCD"

Special match variables such as $1, $2, $`, $&, and $' are set appropriately.

Whitespace in Strings

In class String, whitespace is defined as a contiguous sequence of characters consisting of any mixture of the following:

Whitespace is relevant for these methods:

String Slices

A slice of a string is a substring that is selected by certain criteria.

These instance methods make use of slicing:

Each of the above methods takes arguments that determine the slice to be copied or replaced.

The arguments have several forms. For string string, the forms are:


When non-negative integer argument index is given, the slice is the 1-character substring found in self at character offset index:

'bar'[0]       # => "b"
'bar'[2]       # => "r"
'bar'[20]      # => nil
'тест'[2]      # => "с"
'こんにちは'[4]  # => "は"

When negative integer index is given, the slice begins at the offset given by counting backward from the end of self:

'bar'[-3]         # => "b"
'bar'[-1]         # => "r"
'bar'[-20]        # => nil

string[start, length]

When non-negative integer arguments start and length are given, the slice begins at character offset start, if it exists, and continues for length characters, if available:

'foo'[0, 2]       # => "fo"
'тест'[1, 2]      # => "ес"
'こんにちは'[2, 2]  # => "にち"
# Zero length.
'foo'[2, 0]       # => ""
# Length not entirely available.
'foo'[1, 200]     # => "oo"
# Start out of range.
'foo'[4, 2]      # => nil

Special case: if start is equal to the length of self, the slice is a new empty string:

'foo'[3, 2]   # => ""
'foo'[3, 200] # => ""

When negative start and non-negative length are given, the slice beginning is determined by counting backward from the end of self, and the slice continues for length characters, if available:

'foo'[-2, 2]    # => "oo"
'foo'[-2, 200]  # => "oo"
# Start out of range.
'foo'[-4, 2]     # => nil

When negative length is given, there is no slice:

'foo'[1, -1]  # => nil
'foo'[-2, -1] # => nil


When Range argument range is given, creates a substring of string using the indices in range. The slice is then determined as above:

'foo'[0..1]    # => "fo"
'foo'[0, 2]    # => "fo"

'foo'[2...2]   # => ""
'foo'[2, 0]    # => ""

'foo'[1..200]  # => "oo"
'foo'[1, 200]  # => "oo"

'foo'[4..5]    # => nil
'foo'[4, 2]    # => nil

'foo'[-4..-3]  # => nil
'foo'[-4, 2]   # => nil

'foo'[3..4]    # => ""
'foo'[3, 2]    # => ""

'foo'[-2..-1]  # => "oo"
'foo'[-2, 2]   # => "oo"

'foo'[-2..197] # => "oo"
'foo'[-2, 200] # => "oo"

string[regexp, capture = 0]

When the Regexp argument regexp is given, and the capture argument is 0, the slice is the first matching substring found in self:

'foo'[/o/] # => "o"
'foo'[/x/] # => nil
s = 'hello there'
s[/[aeiou](.)\1/] # => "ell"
s[/[aeiou](.)\1/, 0] # => "ell"

If argument capture is given and not 0, it should be either an capture group index (integer) or a capture group name (string or symbol); the slice is the specified capture (see Groups and Captures at Regexp):

s = 'hello there'
s[/[aeiou](.)\1/, 1] # => "l"
s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "non_vowel"] # => "l"
s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, :vowel] # => "e"

If an invalid capture group index is given, there is no slice. If an invalid capture group name is given, IndexError is raised.


When the single String argument substring is given, returns the substring from self if found, otherwise nil:

'foo'['oo'] # => "oo"
'foo'['xx'] # => nil

What’s Here

First, what’s elsewhere. Class String:

Here, class String provides methods that are useful for:

Methods for Creating a String

Methods for a Frozen/Unfrozen String

Methods for Querying





Methods for Comparing

Methods for Modifying a String

Each of these methods modifies self.






Methods for Converting to New String

Each of these methods returns a new String based on self, often just a modified copy of self.







Methods for Converting to Non-String

Each of these methods converts the contents of self to a non-String.

Characters, Bytes, and Clusters




Strings and Symbols

Methods for Iterating

Continuation objects are generated by Kernel#callcc, after having +require+d continuation. They hold a return address and execution context, allowing a nonlocal return to the end of the callcc block from anywhere within a program. Continuations are somewhat analogous to a structured version of C’s setjmp/longjmp (although they contain more state, so you might consider them closer to threads).

For instance:

require "continuation"
arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
callcc{|cc| $cc = cc}
puts(message = arr.shift)
$ unless message =~ /Max/



Also you can call callcc in other methods:

require "continuation"

def g
  arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
  cc = callcc { |cc| cc }
  puts arr.shift
  return cc, arr.size

def f
  c, size = g if size > 1


This (somewhat contrived) example allows the inner loop to abandon processing early:

require "continuation"
callcc {|cont|
  for i in 0..4
    print "#{i}: "
    for j in i*5...(i+1)*5 if j == 17
      printf "%3d", j


0:   0  1  2  3  4
1:   5  6  7  8  9
2:  10 11 12 13 14
3:  15 16

An Encoding instance represents a character encoding usable in Ruby. It is defined as a constant under the Encoding namespace. It has a name and, optionally, aliases:  # => "US-ASCII"
Encoding::US_ASCII.names # => ["US-ASCII", "ASCII", "ANSI_X3.4-1968", "646"]

A Ruby method that accepts an encoding as an argument will accept:

These are equivalent:

'foo'.encode(Encoding::US_ASCII) # Encoding object.
'foo'.encode('US-ASCII')         # Encoding name.
'foo'.encode('ASCII')            # Encoding alias.

For a full discussion of encodings and their uses, see the Encodings document.

Encoding::ASCII_8BIT is a special-purpose encoding that is usually used for a string of bytes, not a string of characters. But as the name indicates, its characters in the ASCII range are considered as ASCII characters. This is useful when you use other ASCII-compatible encodings.

Raised when the interrupt signal is received, typically because the user has pressed Control-C (on most posix platforms). As such, it is a subclass of SignalException.

  puts "Press ctrl-C when you get bored"
  loop {}
rescue Interrupt => e
  puts "Note: You will typically use Signal.trap instead."


Press ctrl-C when you get bored

then waits until it is interrupted with Control-C and then prints:

Note: You will typically use Signal.trap instead.

Raised when the given index is invalid.

a = [:foo, :bar]
a.fetch(0)   #=> :foo
a[4]         #=> nil
a.fetch(4)   #=> IndexError: index 4 outside of array bounds: -2...2

Raised when encountering Ruby code with an invalid syntax.


raises the exception:

SyntaxError: (eval):1: syntax error, unexpected '=', expecting $end

EncodingError is the base class for encoding errors.

Search took: 15ms  ·  Total Results: 2220