Results for: "tally"

Represents the use of the ‘&&=` operator for assignment to a constant.

Target &&= value
^^^^^^^^^^^^^^^^

Represents writing to a constant path in a context that doesn’t have an explicit value.

Foo::Foo, Bar::Bar = baz
^^^^^^^^  ^^^^^^^^

Represents writing to a constant in a context that doesn’t have an explicit value.

Foo, Bar = baz
^^^  ^^^

Represents writing to a global variable in a context that doesn’t have an explicit value.

$foo, $bar = baz
^^^^  ^^^^

Represents writing to an instance variable in a context that doesn’t have an explicit value.

@foo, @bar = baz
^^^^  ^^^^

Represents writing to a local variable in a context that doesn’t have an explicit value.

foo, bar = baz
^^^  ^^^

Ripper.lex is not guaranteed to lex the entire source document

This class guarantees the whole document is lex-ed by iteratively lexing the document where ripper stopped.

Prism likely doesn’t have the same problem. Once ripper support is removed we can likely reduce the complexity here if not remove the whole concept.

Example usage:

lex = LexAll.new(source: source)
lex.each do |value|
  puts value.line
end

Flags for call nodes.

Raised when a signal is received.

begin
  Process.kill('HUP',Process.pid)
  sleep # wait for receiver to handle signal sent by Process.kill
rescue SignalException => e
  puts "received Exception #{e}"
end

produces:

received Exception SIGHUP

The most standard error types are subclasses of StandardError. A rescue clause without an explicit Exception class will rescue all StandardErrors (and only those).

def foo
  raise "Oups"
end
foo rescue "Hello"   #=> "Hello"

On the other hand:

require 'does/not/exist' rescue "Hi"

raises the exception:

LoadError: no such file to load -- does/not/exist

Raised when encountering Ruby code with an invalid syntax.

eval("1+1=2")

raises the exception:

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

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.

A rational number can be represented as a pair of integer numbers: a/b (b>0), where a is the numerator and b is the denominator. Integer a equals rational a/1 mathematically.

You can create a Rational object explicitly with:

You can convert certain objects to Rationals with:

Examples

Rational(1)      #=> (1/1)
Rational(2, 3)   #=> (2/3)
Rational(4, -6)  #=> (-2/3) # Reduced.
3.to_r           #=> (3/1)
2/3r             #=> (2/3)

You can also create rational objects from floating-point numbers or strings.

Rational(0.3)    #=> (5404319552844595/18014398509481984)
Rational('0.3')  #=> (3/10)
Rational('2/3')  #=> (2/3)

0.3.to_r         #=> (5404319552844595/18014398509481984)
'0.3'.to_r       #=> (3/10)
'2/3'.to_r       #=> (2/3)
0.3.rationalize  #=> (3/10)

A rational object is an exact number, which helps you to write programs without any rounding errors.

10.times.inject(0) {|t| t + 0.1 }              #=> 0.9999999999999999
10.times.inject(0) {|t| t + Rational('0.1') }  #=> (1/1)

However, when an expression includes an inexact component (numerical value or operation), it will produce an inexact result.

Rational(10) / 3   #=> (10/3)
Rational(10) / 3.0 #=> 3.3333333333333335

Rational(-8) ** Rational(1, 3)
                   #=> (1.0000000000000002+1.7320508075688772i)

Class Data provides a convenient way to define simple classes for value-alike objects.

The simplest example of usage:

Measure = Data.define(:amount, :unit)

# Positional arguments constructor is provided
distance = Measure.new(100, 'km')
#=> #<data Measure amount=100, unit="km">

# Keyword arguments constructor is provided
weight = Measure.new(amount: 50, unit: 'kg')
#=> #<data Measure amount=50, unit="kg">

# Alternative form to construct an object:
speed = Measure[10, 'mPh']
#=> #<data Measure amount=10, unit="mPh">

# Works with keyword arguments, too:
area = Measure[amount: 1.5, unit: 'm^2']
#=> #<data Measure amount=1.5, unit="m^2">

# Argument accessors are provided:
distance.amount #=> 100
distance.unit #=> "km"

Constructed object also has a reasonable definitions of == operator, to_h hash conversion, and deconstruct / deconstruct_keys to be used in pattern matching.

::define method accepts an optional block and evaluates it in the context of the newly defined class. That allows to define additional methods:

Measure = Data.define(:amount, :unit) do
  def <=>(other)
    return unless other.is_a?(self.class) && other.unit == unit
    amount <=> other.amount
  end

  include Comparable
end

Measure[3, 'm'] < Measure[5, 'm'] #=> true
Measure[3, 'm'] < Measure[5, 'kg']
# comparison of Measure with Measure failed (ArgumentError)

Data provides no member writers, or enumerators: it is meant to be a storage for immutable atomic values. But note that if some of data members is of a mutable class, Data does no additional immutability enforcement:

Event = Data.define(:time, :weekdays)
event = Event.new('18:00', %w[Tue Wed Fri])
#=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri"]>

# There is no #time= or #weekdays= accessors, but changes are
# still possible:
event.weekdays << 'Sat'
event
#=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri", "Sat"]>

See also Struct, which is a similar concept, but has more container-alike API, allowing to change contents of the object and enumerate it.

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.

The global value false is the only instance of class FalseClass and represents a logically false value in boolean expressions. The class provides operators allowing false to participate correctly in logical expressions.

Raised when Ruby can’t yield as requested.

A typical scenario is attempting to yield when no block is given:

def call_block
  yield 42
end
call_block

raises the exception:

LocalJumpError: no block given (yield)

A more subtle example:

def get_me_a_return
  Proc.new { return 42 }
end
get_me_a_return.call

raises the exception:

LocalJumpError: unexpected return

Raised in case of a stack overflow.

def me_myself_and_i
  me_myself_and_i
end
me_myself_and_i

raises the exception:

SystemStackError: stack level too deep

Manipulates strings like the UNIX Bourne shell

This module manipulates strings according to the word parsing rules of the UNIX Bourne shell.

The shellwords() function was originally a port of shellwords.pl, but modified to conform to the Shell & Utilities volume of the IEEE Std 1003.1-2008, 2016 Edition [1].

Usage

You can use Shellwords to parse a string into a Bourne shell friendly Array.

require 'shellwords'

argv = Shellwords.split('three blind "mice"')
argv #=> ["three", "blind", "mice"]

Once you’ve required Shellwords, you can use the split alias String#shellsplit.

argv = "see how they run".shellsplit
argv #=> ["see", "how", "they", "run"]

They treat quotes as special characters, so an unmatched quote will cause an ArgumentError.

argv = "they all ran after the farmer's wife".shellsplit
     #=> ArgumentError: Unmatched quote: ...

Shellwords also provides methods that do the opposite. Shellwords.escape, or its alias, String#shellescape, escapes shell metacharacters in a string for use in a command line.

filename = "special's.txt"

system("cat -- #{filename.shellescape}")
# runs "cat -- special\\'s.txt"

Note the ‘–’. Without it, cat(1) will treat the following argument as a command line option if it starts with ‘-’. It is guaranteed that Shellwords.escape converts a string to a form that a Bourne shell will parse back to the original string, but it is the programmer’s responsibility to make sure that passing an arbitrary argument to a command does no harm.

Shellwords also comes with a core extension for Array, Array#shelljoin.

dir = "Funny GIFs"
argv = %W[ls -lta -- #{dir}]
system(argv.shelljoin + " | less")
# runs "ls -lta -- Funny\\ GIFs | less"

You can use this method to build a complete command line out of an array of arguments.

Authors

Contact

Resources

1: IEEE Std 1003.1-2008, 2016 Edition, the Shell & Utilities volume

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.

Many operating systems allow signals to be sent to running processes. Some signals have a defined effect on the process, while others may be trapped at the code level and acted upon. For example, your process may trap the USR1 signal and use it to toggle debugging, and may use TERM to initiate a controlled shutdown.

pid = fork do
  Signal.trap("USR1") do
    $debug = !$debug
    puts "Debug now: #$debug"
  end
  Signal.trap("TERM") do
    puts "Terminating..."
    shutdown()
  end
  # . . . do some work . . .
end

Process.detach(pid)

# Controlling program:
Process.kill("USR1", pid)
# ...
Process.kill("USR1", pid)
# ...
Process.kill("TERM", pid)

produces:

Debug now: true
Debug now: false
Terminating...

The list of available signal names and their interpretation is system dependent. Signal delivery semantics may also vary between systems; in particular signal delivery may not always be reliable.

Gem installer command line tool

See ‘gem help install`

Gem uninstaller command line tool

See ‘gem help uninstall`

Search took: 11ms  ·  Total Results: 1651