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
  end
  def get_binding
    binding
  end
end

k1 = Demo.new(99)
b1 = k1.get_binding
k2 = Demo.new(-3)
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
No documentation available

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.

No documentation available

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

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:

Querying

Comparing

Converting

Other

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.rdoc 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.rdoc for details.

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

Note also that a string literal consumes backslashes. See String Literals 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"

Block

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.

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

Counts

Substrings

Encodings

Other

Methods for Comparing

Methods for Modifying a String

Each of these methods modifies self.

Insertion

Substitution

Casing

Encoding

Deletion

Methods for Converting to New String

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

Extension

Encoding

Substitution

Casing

Deletion

Duplication

Methods for Converting to Non-String

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

Characters, Bytes, and Clusters

Splitting

Matching

Numerics

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)
$cc.call unless message =~ /Max/

produces:

Freddie
Herbie
Ron
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
end

def f
  c, size = g
  c.call(c) if size > 1
end

f

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
      cont.call() if j == 17
      printf "%3d", j
    end
  end
}
puts

produces:

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:

Encoding::ISO_8859_1.name
#=> "ISO-8859-1"

Encoding::ISO_8859_1.names
#=> ["ISO-8859-1", "ISO8859-1"]

Ruby methods dealing with encodings return or accept Encoding instances as arguments (when a method accepts an Encoding instance as an argument, it can be passed an Encoding name or alias instead).

"some string".encoding
#=> #<Encoding:UTF-8>

string = "some string".encode(Encoding::ISO_8859_1)
#=> "some string"
string.encoding
#=> #<Encoding:ISO-8859-1>

"some string".encode "ISO-8859-1"
#=> "some string"

Encoding::ASCII_8BIT is a special encoding that is usually used for a byte string, not a character string. But as the name insists, its characters in the range of ASCII are considered as ASCII characters. This is useful when you use ASCII-8BIT characters with other ASCII compatible characters.

Changing an encoding

The associated Encoding of a String can be changed in two different ways.

First, it is possible to set the Encoding of a string to a new Encoding without changing the internal byte representation of the string, with String#force_encoding. This is how you can tell Ruby the correct encoding of a string.

string
#=> "R\xC3\xA9sum\xC3\xA9"
string.encoding
#=> #<Encoding:ISO-8859-1>
string.force_encoding(Encoding::UTF_8)
#=> "R\u00E9sum\u00E9"

Second, it is possible to transcode a string, i.e. translate its internal byte representation to another encoding. Its associated encoding is also set to the other encoding. See String#encode for the various forms of transcoding, and the Encoding::Converter class for additional control over the transcoding process.

string
#=> "R\u00E9sum\u00E9"
string.encoding
#=> #<Encoding:UTF-8>
string = string.encode!(Encoding::ISO_8859_1)
#=> "R\xE9sum\xE9"
string.encoding
#=> #<Encoding::ISO-8859-1>

Script encoding

All Ruby script code has an associated Encoding which any String literal created in the source code will be associated to.

The default script encoding is Encoding::UTF_8 after v2.0, but it can be changed by a magic comment on the first line of the source code file (or second line, if there is a shebang line on the first). The comment must contain the word coding or encoding, followed by a colon, space and the Encoding name or alias:

# encoding: UTF-8

"some string".encoding
#=> #<Encoding:UTF-8>

The __ENCODING__ keyword returns the script encoding of the file which the keyword is written:

# encoding: ISO-8859-1

__ENCODING__
#=> #<Encoding:ISO-8859-1>

ruby -K will change the default locale encoding, but this is not recommended. Ruby source files should declare its script encoding by a magic comment even when they only depend on US-ASCII strings or regular expressions.

Locale encoding

The default encoding of the environment. Usually derived from locale.

see Encoding.locale_charmap, Encoding.find(‘locale’)

Filesystem encoding

The default encoding of strings from the filesystem of the environment. This is used for strings of file names or paths.

see Encoding.find(‘filesystem’)

External encoding

Each IO object has an external encoding which indicates the encoding that Ruby will use to read its data. By default Ruby sets the external encoding of an IO object to the default external encoding. The default external encoding is set by locale encoding or the interpreter -E option. Encoding.default_external returns the current value of the external encoding.

ENV["LANG"]
#=> "UTF-8"
Encoding.default_external
#=> #<Encoding:UTF-8>

$ ruby -E ISO-8859-1 -e "p Encoding.default_external"
#<Encoding:ISO-8859-1>

$ LANG=C ruby -e 'p Encoding.default_external'
#<Encoding:US-ASCII>

The default external encoding may also be set through Encoding.default_external=, but you should not do this as strings created before and after the change will have inconsistent encodings. Instead use ruby -E to invoke ruby with the correct external encoding.

When you know that the actual encoding of the data of an IO object is not the default external encoding, you can reset its external encoding with IO#set_encoding or set it at IO object creation (see IO.new options).

Internal encoding

To process the data of an IO object which has an encoding different from its external encoding, you can set its internal encoding. Ruby will use this internal encoding to transcode the data when it is read from the IO object.

Conversely, when data is written to the IO object it is transcoded from the internal encoding to the external encoding of the IO object.

The internal encoding of an IO object can be set with IO#set_encoding or at IO object creation (see IO.new options).

The internal encoding is optional and when not set, the Ruby default internal encoding is used. If not explicitly set this default internal encoding is nil meaning that by default, no transcoding occurs.

The default internal encoding can be set with the interpreter option -E. Encoding.default_internal returns the current internal encoding.

$ ruby -e 'p Encoding.default_internal'
nil

$ ruby -E ISO-8859-1:UTF-8 -e "p [Encoding.default_external, \
  Encoding.default_internal]"
[#<Encoding:ISO-8859-1>, #<Encoding:UTF-8>]

The default internal encoding may also be set through Encoding.default_internal=, but you should not do this as strings created before and after the change will have inconsistent encodings. Instead use ruby -E to invoke ruby with the correct internal encoding.

IO encoding example

In the following example a UTF-8 encoded string “Ru00E9sumu00E9” is transcoded for output to ISO-8859-1 encoding, then read back in and transcoded to UTF-8:

string = "R\u00E9sum\u00E9"

open("transcoded.txt", "w:ISO-8859-1") do |io|
  io.write(string)
end

puts "raw text:"
p File.binread("transcoded.txt")
puts

open("transcoded.txt", "r:ISO-8859-1:UTF-8") do |io|
  puts "transcoded text:"
  p io.read
end

While writing the file, the internal encoding is not specified as it is only necessary for reading. While reading the file both the internal and external encoding must be specified to obtain the correct result.

$ ruby t.rb
raw text:
"R\xE9sum\xE9"

transcoded text:
"R\u00E9sum\u00E9"

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.

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

produces:

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.

eval("1+1=2")

raises the exception:

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

EncodingError is the base class for encoding errors.

BigDecimal provides arbitrary-precision floating point decimal arithmetic.

Introduction

Ruby provides built-in support for arbitrary precision integer arithmetic.

For example:

42**13  #=>   1265437718438866624512

BigDecimal provides similar support for very large or very accurate floating point numbers.

Decimal arithmetic is also useful for general calculation, because it provides the correct answers people expect–whereas normal binary floating point arithmetic often introduces subtle errors because of the conversion between base 10 and base 2.

For example, try:

sum = 0
10_000.times do
  sum = sum + 0.0001
end
print sum #=> 0.9999999999999062

and contrast with the output from:

require 'bigdecimal'

sum = BigDecimal("0")
10_000.times do
  sum = sum + BigDecimal("0.0001")
end
print sum #=> 0.1E1

Similarly:

(BigDecimal("1.2") - BigDecimal("1.0")) == BigDecimal("0.2") #=> true

(1.2 - 1.0) == 0.2 #=> false

A Note About Precision

For a calculation using a BigDecimal and another value, the precision of the result depends on the type of value:

Special features of accurate decimal arithmetic

Because BigDecimal is more accurate than normal binary floating point arithmetic, it requires some special values.

Infinity

BigDecimal sometimes needs to return infinity, for example if you divide a value by zero.

BigDecimal("1.0") / BigDecimal("0.0")  #=> Infinity
BigDecimal("-1.0") / BigDecimal("0.0")  #=> -Infinity

You can represent infinite numbers to BigDecimal using the strings 'Infinity', '+Infinity' and '-Infinity' (case-sensitive)

Not a Number

When a computation results in an undefined value, the special value NaN (for ‘not a number’) is returned.

Example:

BigDecimal("0.0") / BigDecimal("0.0") #=> NaN

You can also create undefined values.

NaN is never considered to be the same as any other value, even NaN itself:

n = BigDecimal('NaN')
n == 0.0 #=> false
n == n #=> false

Positive and negative zero

If a computation results in a value which is too small to be represented as a BigDecimal within the currently specified limits of precision, zero must be returned.

If the value which is too small to be represented is negative, a BigDecimal value of negative zero is returned.

BigDecimal("1.0") / BigDecimal("-Infinity") #=> -0.0

If the value is positive, a value of positive zero is returned.

BigDecimal("1.0") / BigDecimal("Infinity") #=> 0.0

(See BigDecimal.mode for how to specify limits of precision.)

Note that -0.0 and 0.0 are considered to be the same for the purposes of comparison.

Note also that in mathematics, there is no particular concept of negative or positive zero; true mathematical zero has no sign.

bigdecimal/util

When you require bigdecimal/util, the to_d method will be available on BigDecimal and the native Integer, Float, Rational, and String classes:

require 'bigdecimal/util'

42.to_d         # => 0.42e2
0.5.to_d        # => 0.5e0
(2/3r).to_d(3)  # => 0.667e0
"0.5".to_d      # => 0.5e0

License

Copyright © 2002 by Shigeo Kobayashi <shigeo@tinyforest.gr.jp>.

BigDecimal is released under the Ruby and 2-clause BSD licenses. See LICENSE.txt for details.

Maintained by mrkn <mrkn@mrkn.jp> and ruby-core members.

Documented by zzak <zachary@zacharyscott.net>, mathew <meta@pobox.com>, and many other contributors.

No documentation available
Search took: 27ms  ·  Total Results: 1759