Results for: "minmax"

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

Methods for Working with JSON

These methods are provided by the JSON gem. To make these methods available:

require 'json/add/bigdecimal'

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.

The Addrinfo class maps struct addrinfo to ruby. This structure identifies an Internet host and a service.

IO streams for strings, with access similar to IO; see IO.

About the Examples

Examples on this page assume that StringIO has been required:

require 'stringio'

StringScanner provides for lexical scanning operations on a String. Here is an example of its usage:

require 'strscan'

s = StringScanner.new('This is an example string')
s.eos?               # -> false

p s.scan(/\w+/)      # -> "This"
p s.scan(/\w+/)      # -> nil
p s.scan(/\s+/)      # -> " "
p s.scan(/\s+/)      # -> nil
p s.scan(/\w+/)      # -> "is"
s.eos?               # -> false

p s.scan(/\s+/)      # -> " "
p s.scan(/\w+/)      # -> "an"
p s.scan(/\s+/)      # -> " "
p s.scan(/\w+/)      # -> "example"
p s.scan(/\s+/)      # -> " "
p s.scan(/\w+/)      # -> "string"
s.eos?               # -> true

p s.scan(/\s+/)      # -> nil
p s.scan(/\w+/)      # -> nil

Scanning a string means remembering the position of a scan pointer, which is just an index. The point of scanning is to move forward a bit at a time, so matches are sought after the scan pointer; usually immediately after it.

Given the string “test string”, here are the pertinent scan pointer positions:

  t e s t   s t r i n g
0 1 2 ...             1
                      0

When you scan for a pattern (a regular expression), the match must occur at the character after the scan pointer. If you use scan_until, then the match can occur anywhere after the scan pointer. In both cases, the scan pointer moves just beyond the last character of the match, ready to scan again from the next character onwards. This is demonstrated by the example above.

Method Categories

There are other methods besides the plain scanners. You can look ahead in the string without actually scanning. You can access the most recent match. You can modify the string being scanned, reset or terminate the scanner, find out or change the position of the scan pointer, skip ahead, and so on.

Advancing the Scan Pointer

Looking Ahead

Finding Where we Are

Setting Where we Are

Match Data

Miscellaneous

There are aliases to several of the methods.

WIN32OLE

WIN32OLE objects represent OLE Automation object in Ruby.

By using WIN32OLE, you can access OLE server like VBScript.

Here is sample script.

require 'win32ole'

excel = WIN32OLE.new('Excel.Application')
excel.visible = true
workbook = excel.Workbooks.Add();
worksheet = workbook.Worksheets(1);
worksheet.Range("A1:D1").value = ["North","South","East","West"];
worksheet.Range("A2:B2").value = [5.2, 10];
worksheet.Range("C2").value = 8;
worksheet.Range("D2").value = 20;

range = worksheet.Range("A1:D2");
range.select
chart = workbook.Charts.Add;

workbook.saved = true;

excel.ActiveWorkbook.Close(0);
excel.Quit();

Unfortunately, Win32OLE doesn’t support the argument passed by reference directly. Instead, Win32OLE provides WIN32OLE::ARGV or WIN32OLE_VARIANT object. If you want to get the result value of argument passed by reference, you can use WIN32OLE::ARGV or WIN32OLE_VARIANT.

oleobj.method(arg1, arg2, refargv3)
puts WIN32OLE::ARGV[2]   # the value of refargv3 after called oleobj.method

or

refargv3 = WIN32OLE_VARIANT.new(XXX,
            WIN32OLE::VARIANT::VT_BYREF|WIN32OLE::VARIANT::VT_XXX)
oleobj.method(arg1, arg2, refargv3)
p refargv3.value # the value of refargv3 after called oleobj.method.

Raised when OLE processing failed.

EX:

obj = WIN32OLE.new("NonExistProgID")

raises the exception:

WIN32OLERuntimeError: unknown OLE server: `NonExistProgID'
    HRESULT error code:0x800401f3
      Invalid class string

MatchData encapsulates the result of matching a Regexp against string. It is returned by Regexp#match and String#match, and also stored in a global variable returned by Regexp.last_match.

Usage:

url = 'https://docs.ruby-lang.org/en/2.5.0/MatchData.html'
m = url.match(/(\d\.?)+/)   # => #<MatchData "2.5.0" 1:"0">
m.string                    # => "https://docs.ruby-lang.org/en/2.5.0/MatchData.html"
m.regexp                    # => /(\d\.?)+/
# entire matched substring:
m[0]                        # => "2.5.0"

# Working with unnamed captures
m = url.match(%r{([^/]+)/([^/]+)\.html$})
m.captures                  # => ["2.5.0", "MatchData"]
m[1]                        # => "2.5.0"
m.values_at(1, 2)           # => ["2.5.0", "MatchData"]

# Working with named captures
m = url.match(%r{(?<version>[^/]+)/(?<module>[^/]+)\.html$})
m.captures                  # => ["2.5.0", "MatchData"]
m.named_captures            # => {"version"=>"2.5.0", "module"=>"MatchData"}
m[:version]                 # => "2.5.0"
m.values_at(:version, :module)
                            # => ["2.5.0", "MatchData"]
# Numerical indexes are working, too
m[1]                        # => "2.5.0"
m.values_at(1, 2)           # => ["2.5.0", "MatchData"]

Global variables equivalence

Parts of last MatchData (returned by Regexp.last_match) are also aliased as global variables:

See also “Special global variables” section in Regexp documentation.

This class implements a pretty printing algorithm. It finds line breaks and nice indentations for grouped structure.

By default, the class assumes that primitive elements are strings and each byte in the strings have single column in width. But it can be used for other situations by giving suitable arguments for some methods:

There are several candidate uses:

Bugs

Report any bugs at bugs.ruby-lang.org

References

Christian Lindig, Strictly Pretty, March 2000, lindig.github.io/papers/strictly-pretty-2000.pdf

Philip Wadler, A prettier printer, March 1998, homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier

Author

Tanaka Akira <akr@fsij.org>

A class that provides the functionality of Kernel#set_trace_func in a nice Object-Oriented API.

Example

We can use TracePoint to gather information specifically for exceptions:

trace = TracePoint.new(:raise) do |tp|
    p [tp.lineno, tp.event, tp.raised_exception]
end
#=> #<TracePoint:disabled>

trace.enable
#=> false

0 / 0
#=> [5, :raise, #<ZeroDivisionError: divided by 0>]

Events

If you don’t specify the type of events you want to listen for, TracePoint will include all available events.

Note do not depend on current event set, as this list is subject to change. Instead, it is recommended you specify the type of events you want to use.

To filter what is traced, you can pass any of the following as events:

:line

execute an expression or statement on a new line

:class

start a class or module definition

:end

finish a class or module definition

:call

call a Ruby method

:return

return from a Ruby method

:c_call

call a C-language routine

:c_return

return from a C-language routine

:raise

raise an exception

:rescue

rescue an exception

:b_call

event hook at block entry

:b_return

event hook at block ending

:a_call

event hook at all calls (call, b_call, and c_call)

:a_return

event hook at all returns (return, b_return, and c_return)

:thread_begin

event hook at thread beginning

:thread_end

event hook at thread ending

:fiber_switch

event hook at fiber switch

:script_compiled

new Ruby code compiled (with eval, load or require)

The Warning module contains a single method named warn, and the module extends itself, making Warning.warn available. Warning.warn is called for all warnings issued by Ruby. By default, warnings are printed to $stderr.

Changing the behavior of Warning.warn is useful to customize how warnings are handled by Ruby, for instance by filtering some warnings, and/or outputting warnings somewhere other than $stderr.

If you want to change the behavior of Warning.warn you should use Warning.extend(MyNewModuleWithWarnMethod) and you can use super to get the default behavior of printing the warning to $stderr.

Example:

module MyWarningFilter
  def warn(message, category: nil, **kwargs)
    if /some warning I want to ignore/.match?(message)
      # ignore
    else
      super
    end
  end
end
Warning.extend MyWarningFilter

You should never redefine Warning#warn (the instance method), as that will then no longer provide a way to use the default behavior.

The warning gem provides convenient ways to customize Warning.warn.

Provides mathematical functions.

Example:

require "bigdecimal/math"

include BigMath

a = BigDecimal((PI(100)/2).to_s)
puts sin(a,100) # => 0.99999999999999999999......e0

Implements bindings to Win32 SSPI functions, focused on authentication to a proxy server over HTTP.

The Benchmark module provides methods to measure and report the time used to execute Ruby code.

The result:

              user     system      total        real
for:      1.010000   0.000000   1.010000 (  1.015688)
times:    1.000000   0.000000   1.000000 (  1.003611)
upto:     1.030000   0.000000   1.030000 (  1.028098)

The Find module supports the top-down traversal of a set of file paths.

For example, to total the size of all files under your home directory, ignoring anything in a “dot” directory (e.g. $HOME/.ssh):

require 'find'

total_size = 0

Find.find(ENV["HOME"]) do |path|
  if FileTest.directory?(path)
    if File.basename(path).start_with?('.')
      Find.prune       # Don't look any further into this directory.
    else
      next
    end
  else
    total_size += FileTest.size(path)
  end
end

SingleForwardable can be used to setup delegation at the object level as well.

printer = String.new
printer.extend SingleForwardable        # prepare object for delegation
printer.def_delegator "STDOUT", "puts"  # add delegation for STDOUT.puts()
printer.puts "Howdy!"

Also, SingleForwardable can be used to set up delegation for a Class or Module.

class Implementation
  def self.service
    puts "serviced!"
  end
end

module Facade
  extend SingleForwardable
  def_delegator :Implementation, :service
end

Facade.service #=> serviced!

If you want to use both Forwardable and SingleForwardable, you can use methods def_instance_delegator and def_single_delegator, etc.

No documentation available
No documentation available

A module to implement the Linda distributed computing paradigm in Ruby.

Rinda is part of DRb (dRuby).

Example(s)

See the sample/drb/ directory in the Ruby distribution, from 1.8.2 onwards.

The Singleton module implements the Singleton pattern.

Usage

To use Singleton, include the module in your class.

class Klass
   include Singleton
   # ...
end

This ensures that only one instance of Klass can be created.

a,b = Klass.instance, Klass.instance

a == b
# => true

Klass.new
# => NoMethodError - new is private ...

The instance is created at upon the first call of Klass.instance().

class OtherKlass
  include Singleton
  # ...
end

ObjectSpace.each_object(OtherKlass){}
# => 0

OtherKlass.instance
ObjectSpace.each_object(OtherKlass){}
# => 1

This behavior is preserved under inheritance and cloning.

Implementation

This above is achieved by:

Singleton and Marshal

By default Singleton’s _dump(depth) returns the empty string. Marshalling by default will strip state information, e.g. instance variables from the instance. Classes using Singleton can provide custom _load(str) and _dump(depth) methods to retain some of the previous state of the instance.

require 'singleton'

class Example
  include Singleton
  attr_accessor :keep, :strip
  def _dump(depth)
    # this strips the @strip information from the instance
    Marshal.dump(@keep, depth)
  end

  def self._load(str)
    instance.keep = Marshal.load(str)
    instance
  end
end

a = Example.instance
a.keep = "keep this"
a.strip = "get rid of this"

stored_state = Marshal.dump(a)

a.keep = nil
a.strip = nil
b = Marshal.load(stored_state)
p a == b  #  => true
p a.keep  #  => "keep this"
p a.strip #  => nil
No documentation available

define UnicodeNormalize module here so that we don’t have to look it up

The marshaling library converts collections of Ruby objects into a byte stream, allowing them to be stored outside the currently active script. This data may subsequently be read and the original objects reconstituted.

Marshaled data has major and minor version numbers stored along with the object information. In normal use, marshaling can only load data written with the same major version number and an equal or lower minor version number. If Ruby’s “verbose” flag is set (normally using -d, -v, -w, or –verbose) the major and minor numbers must match exactly. Marshal versioning is independent of Ruby’s version numbers. You can extract the version by reading the first two bytes of marshaled data.

str = Marshal.dump("thing")
RUBY_VERSION   #=> "1.9.0"
str[0].ord     #=> 4
str[1].ord     #=> 8

Some objects cannot be dumped: if the objects to be dumped include bindings, procedure or method objects, instances of class IO, or singleton objects, a TypeError will be raised.

If your class has special serialization needs (for example, if you want to serialize in some specific format), or if it contains objects that would otherwise not be serializable, you can implement your own serialization strategy.

There are two methods of doing this, your object can define either marshal_dump and marshal_load or _dump and _load. marshal_dump will take precedence over _dump if both are defined. marshal_dump may result in smaller Marshal strings.

Security considerations

By design, Marshal.load can deserialize almost any class loaded into the Ruby process. In many cases this can lead to remote code execution if the Marshal data is loaded from an untrusted source.

As a result, Marshal.load is not suitable as a general purpose serialization format and you should never unmarshal user supplied input or other untrusted data.

If you need to deserialize untrusted data, use JSON or another serialization format that is only able to load simple, ‘primitive’ types such as String, Array, Hash, etc. Never allow user input to specify arbitrary types to deserialize into.

marshal_dump and marshal_load

When dumping an object the method marshal_dump will be called. marshal_dump must return a result containing the information necessary for marshal_load to reconstitute the object. The result can be any object.

When loading an object dumped using marshal_dump the object is first allocated then marshal_load is called with the result from marshal_dump. marshal_load must recreate the object from the information in the result.

Example:

class MyObj
  def initialize name, version, data
    @name    = name
    @version = version
    @data    = data
  end

  def marshal_dump
    [@name, @version]
  end

  def marshal_load array
    @name, @version = array
  end
end

_dump and _load

Use _dump and _load when you need to allocate the object you’re restoring yourself.

When dumping an object the instance method _dump is called with an Integer which indicates the maximum depth of objects to dump (a value of -1 implies that you should disable depth checking). _dump must return a String containing the information necessary to reconstitute the object.

The class method _load should take a String and use it to return an object of the same class.

Example:

class MyObj
  def initialize name, version, data
    @name    = name
    @version = version
    @data    = data
  end

  def _dump level
    [@name, @version].join ':'
  end

  def self._load args
    new(*args.split(':'))
  end
end

Since Marshal.dump outputs a string you can have _dump return a Marshal string which is Marshal.loaded in _load for complex objects.

Module Math provides methods for basic trigonometric, logarithmic, and transcendental functions, and for extracting roots.

You can write its constants and method calls thus:

Math::PI      # => 3.141592653589793
Math::E       # => 2.718281828459045
Math.sin(0.0) # => 0.0
Math.cos(0.0) # => 1.0

If you include module Math, you can write simpler forms:

include Math
PI       # => 3.141592653589793
E        # => 2.718281828459045
sin(0.0) # => 0.0
cos(0.0) # => 1.0

For simplicity, the examples here assume:

include Math
INFINITY = Float::INFINITY

The domains and ranges for the methods are denoted by open or closed intervals, using, respectively, parentheses or square brackets:

Many values returned by Math methods are numerical approximations. This is because many such values are, in mathematics, of infinite precision, while in numerical computation the precision is finite.

Thus, in mathematics, cos(π/2) is exactly zero, but in our computation cos(PI/2) is a number very close to zero:

cos(PI/2) # => 6.123031769111886e-17

For very large and very small returned values, we have added formatted numbers for clarity:

tan(PI/2)  # => 1.633123935319537e+16   # 16331239353195370.0
tan(PI)    # => -1.2246467991473532e-16 # -0.0000000000000001

See class Float for the constants that affect Ruby’s floating-point arithmetic.

What’s Here

Trigonometric Functions

Inverse Trigonometric Functions

Hyperbolic Trigonometric Functions

Inverse Hyperbolic Trigonometric Functions

Exponentiation and Logarithmic Functions

Fraction and Exponent Functions

Root Functions

Error Functions

Gamma Functions

Hypotenuse Function

This exception is raised if the required unicode support is missing on the system. Usually this means that the iconv library is not installed.

Exception raised when there is an invalid encoding detected

Search took: 12ms  ·  Total Results: 2220