Raised when a given numerical value is out of range.
[1, 2, 3].drop(1 << 100)
raises the exception:
RangeError: bignum too big to convert into `long'
ScriptError
is the superclass for errors raised when a script can not be executed because of a LoadError
, NotImplementedError
or a SyntaxError
. Note these type of ScriptErrors
are not StandardError
and will not be rescued unless it is specified explicitly (or its ancestor Exception
).
No longer used by internal code.
SystemCallError
is the base class for all low-level platform-dependent errors.
The errors available on the current platform are subclasses of SystemCallError
and are defined in the Errno
module.
File.open("does/not/exist")
raises the exception:
Errno::ENOENT: No such file or directory - does/not/exist
A Range object represents a collection of values that are between given begin and end values.
You can create an Range object explicitly with:
A range literal:
# Ranges that use '..' to include the given end value. (1..4).to_a # => [1, 2, 3, 4] ('a'..'d').to_a # => ["a", "b", "c", "d"] # Ranges that use '...' to exclude the given end value. (1...4).to_a # => [1, 2, 3] ('a'...'d').to_a # => ["a", "b", "c"]
# Ranges that by default include the given end value. Range.new(1, 4)
.to_a # => [1, 2, 3, 4] Range.new
(‘a’, ‘d’).to_a # => [“a”, “b”, “c”, “d”] # Ranges that use third argument exclude_end
to exclude the given end value. Range.new(1, 4, true)
.to_a # => [1, 2, 3] Range.new
(‘a’, ‘d’, true).to_a # => [“a”, “b”, “c”]
A beginless range has a definite end value, but a nil
begin value. Such a range includes all values up to the end value.
r = (..4) # => nil..4 r.begin # => nil r.include?(-50) # => true r.include?(4) # => true r = (...4) # => nil...4 r.include?(4) # => false Range.new(nil, 4) # => nil..4 Range.new(nil, 4, true) # => nil...4
A beginless range may be used to slice an array:
a = [1, 2, 3, 4] # Include the third array element in the slice r = (..2) # => nil..2 a[r] # => [1, 2, 3] # Exclude the third array element from the slice r = (...2) # => nil...2 a[r] # => [1, 2]
Method
each
for a beginless range raises an exception.
An endless range has a definite begin value, but a nil
end value. Such a range includes all values from the begin value.
r = (1..) # => 1.. r.end # => nil r.include?(50) # => true Range.new(1, nil) # => 1..
The literal for an endless range may be written with either two dots or three. The range has the same elements, either way. But note that the two are not equal:
r0 = (1..) # => 1.. r1 = (1...) # => 1... r0.begin == r1.begin # => true r0.end == r1.end # => true r0 == r1 # => false
An endless range may be used to slice an array:
a = [1, 2, 3, 4] r = (2..) # => 2.. a[r] # => [3, 4]
Method
each
for an endless range calls the given block indefinitely:
a = [] r = (1..) r.each do |i| a.push(i) if i.even? break if i > 10 end a # => [2, 4, 6, 8, 10]
A range can be both beginless and endless. For literal beginless, endless ranges, at least the beginning or end of the range must be given as an explicit nil value. It is recommended to use an explicit nil beginning and implicit nil end, since that is what Ruby
uses for Range#inspect
:
(nil..) # => (nil..) (..nil) # => (nil..) (nil..nil) # => (nil..)
An object may be put into a range if its class implements instance method #<=>
. Ruby
core classes that do so include Array
, Complex
, File::Stat
, Float
, Integer
, Kernel
, Module
, Numeric
, Rational
, String
, Symbol
, and Time
.
Example:
t0 = Time.now # => 2021-09-19 09:22:48.4854986 -0500 t1 = Time.now # => 2021-09-19 09:22:56.0365079 -0500 t2 = Time.now # => 2021-09-19 09:23:08.5263283 -0500 (t0..t2).include?(t1) # => true (t0..t1).include?(t2) # => false
A range can be iterated over only if its elements implement instance method succ
. Ruby
core classes that do so include Integer
, String
, and Symbol
(but not the other classes mentioned above).
Iterator methods include:
Included from module Enumerable: each_entry
, each_with_index
, each_with_object
, each_slice
, each_cons
, and reverse_each
.
Example:
a = [] (1..4).each {|i| a.push(i) } a # => [1, 2, 3, 4]
A user-defined class that is to be used in a range must implement instance method #<=>
; see Integer#<=>
. To make iteration available, it must also implement instance method succ
; see Integer#succ
.
The class below implements both #<=>
and succ
, and so can be used both to construct ranges and to iterate over them. Note that the Comparable
module is included so the ==
method is defined in terms of #<=>
.
# Represent a string of 'X' characters. class Xs include Comparable attr_accessor :length def initialize(n) @length = n end def succ Xs.new(@length + 1) end def <=>(other) @length <=> other.length end def to_s sprintf "%2d #{inspect}", @length end def inspect 'X' * @length end end r = Xs.new(3)..Xs.new(6) #=> XXX..XXXXXX r.to_a #=> [XXX, XXXX, XXXXX, XXXXXX] r.include?(Xs.new(5)) #=> true r.include?(Xs.new(7)) #=> false
First, what’s elsewhere. Class
Range:
Inherits from class Object.
Includes module Enumerable, which provides dozens of additional methods.
Here, class Range provides methods that are useful for:
::new
: Returns a new range.
begin
: Returns the begin value given for self
.
bsearch
: Returns an element from self
selected by a binary search.
count
: Returns a count of elements in self
.
end
: Returns the end value given for self
.
exclude_end?
: Returns whether the end object is excluded.
first
: Returns the first elements of self
.
hash
: Returns the integer hash code.
last
: Returns the last elements of self
.
max
: Returns the maximum values in self
.
min
: Returns the minimum values in self
.
minmax
: Returns the minimum and maximum values in self
.
size
: Returns the count of elements in self
.
==
: Returns whether a given object is equal to self
(uses ==
).
===
: Returns whether the given object is between the begin and end values.
cover?
: Returns whether a given object is within self
.
eql?
: Returns whether a given object is equal to self
(uses eql?
).
include?
(aliased as member?
): Returns whether a given object is an element of self
.
%
: Requires argument n
; calls the block with each n
-th element of self
.
each
: Calls the block with each element of self
.
step
: Takes optional argument n
(defaults to 1); calls the block with each n
-th element of self
.
inspect
: Returns a string representation of self
(uses inspect
).
to_a
(aliased as entries
): Returns elements of self
in an array.
::json_create
: Returns a new Range object constructed from the given object.
as_json
: Returns a 2-element hash representing self
.
to_json
: Returns a JSON string representing self
.
To make these methods available:
require 'json/add/range'
Ripper
is a Ruby
script parser.
You can get information from the parser with event-based style. Information such as abstract syntax trees or simple lexical analysis of the Ruby
program.
Ripper
provides an easy interface for parsing your program into a symbolic expression tree (or S-expression).
Understanding the output of the parser may come as a challenge, it’s recommended you use PP
to format the output for legibility.
require 'ripper' require 'pp' pp Ripper.sexp('def hello(world) "Hello, #{world}!"; end') #=> [:program, [[:def, [:@ident, "hello", [1, 4]], [:paren, [:params, [[:@ident, "world", [1, 10]]], nil, nil, nil, nil, nil, nil]], [:bodystmt, [[:string_literal, [:string_content, [:@tstring_content, "Hello, ", [1, 18]], [:string_embexpr, [[:var_ref, [:@ident, "world", [1, 27]]]]], [:@tstring_content, "!", [1, 33]]]]], nil, nil, nil]]]]
You can see in the example above, the expression starts with :program
.
From here, a method definition at :def
, followed by the method’s identifier :@ident
. After the method’s identifier comes the parentheses :paren
and the method parameters under :params
.
Next is the method body, starting at :bodystmt
(stmt
meaning statement), which contains the full definition of the method.
In our case, we’re simply returning a String
, so next we have the :string_literal
expression.
Within our :string_literal
you’ll notice two @tstring_content
, this is the literal part for Hello,
and !
. Between the two @tstring_content
statements is a :string_embexpr
, where embexpr is an embedded expression. Our expression consists of a local variable, or var_ref
, with the identifier (@ident
) of world
.
ruby 1.9 (support CVS HEAD only)
bison 1.28 or later (Other yaccs do not work)
Ruby
License.
Minero Aoki
aamine@loveruby.net
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
The class of the singleton object true
.
Several of its methods act as operators:
One other method:
This module provides a framework for message digest libraries.
You may want to look at OpenSSL::Digest
as it supports more algorithms.
A cryptographic hash function is a procedure that takes data and returns a fixed bit string: the hash value, also known as digest. Hash
functions are also called one-way functions, it is easy to compute a digest from a message, but it is infeasible to generate a message from a digest.
require 'digest' # Compute a complete digest Digest::SHA256.digest 'message' #=> "\xABS\n\x13\xE4Y..." sha256 = Digest::SHA256.new sha256.digest 'message' #=> "\xABS\n\x13\xE4Y..." # Other encoding formats Digest::SHA256.hexdigest 'message' #=> "ab530a13e459..." Digest::SHA256.base64digest 'message' #=> "q1MKE+RZFJgr..." # Compute digest by chunks md5 = Digest::MD5.new md5.update 'message1' md5 << 'message2' # << is an alias for update md5.hexdigest #=> "94af09c09bb9..." # Compute digest for a file sha256 = Digest::SHA256.file 'testfile' sha256.hexdigest
Additionally digests can be encoded in “bubble babble” format as a sequence of consonants and vowels which is more recognizable and comparable than a hexadecimal digest.
require 'digest/bubblebabble' Digest::SHA256.bubblebabble 'message' #=> "xopoh-fedac-fenyh-..."
See the bubble babble specification at web.mit.edu/kenta/www/one/bubblebabble/spec/jrtrjwzi/draft-huima-01.txt.
Digest
algorithms Different digest algorithms (or hash functions) are available:
MD5
See RFC 1321 The MD5
Message-Digest Algorithm
As Digest::RMD160
. See homes.esat.kuleuven.be/~bosselae/ripemd160.html.
SHA1
See FIPS 180 Secure Hash
Standard.
SHA2
family
See FIPS 180 Secure Hash
Standard which defines the following algorithms:
The latest versions of the FIPS publications can be found here: csrc.nist.gov/publications/PubsFIPS.html.
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.
require 'monitor.rb' buf = [] buf.extend(MonitorMixin) empty_cond = buf.new_cond # consumer Thread.start do loop do buf.synchronize do empty_cond.wait_while { buf.empty? } print buf.shift end end end # producer while line = ARGF.gets buf.synchronize do buf.push(line) empty_cond.signal end end
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.
Class
include require 'monitor' class SynchronizedArray < Array include MonitorMixin def initialize(*args) super(*args) end alias :old_shift :shift alias :old_unshift :unshift def shift(n=1) self.synchronize do self.old_shift(n) end end def unshift(item) self.synchronize do self.old_unshift(item) end end # other methods ... end
SynchronizedArray
implements an Array
with synchronized access to items. This Class
is implemented as subclass of Array
which includes the MonitorMixin
module.
FileTest
implements file test operations similar to those used in File::Stat
. It exists as a standalone module, and its methods are also insinuated into the File
class. (Note that this is not done by inclusion: the interpreter cheats).
Include the English
library file in a Ruby
script, and you can reference the global variables such as $_
using less cryptic names, listed below.
Without ‘English’:
$\ = ' -- ' "waterbuffalo" =~ /buff/ print $', $$, "\n"
With English:
require "English" $OUTPUT_FIELD_SEPARATOR = ' -- ' "waterbuffalo" =~ /buff/ print $POSTMATCH, $PID, "\n"
Below is a full list of descriptive aliases and their associated global variable:
$!
$@
$;
$;
$,
$,
$/
$/
$\
$\
$.
$.
$_
$>
$<
$$
$$
$?
$~
$*
$&
$‘
$‘
$+
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
URI
is a module providing classes to handle Uniform Resource Identifiers (RFC2396).
Uniform way of handling URIs.
Flexibility to introduce custom URI
schemes.
Flexibility to have an alternate URI::Parser (or just different patterns and regexp’s).
require 'uri' uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413") #=> #<URI::HTTP http://foo.com/posts?id=30&limit=5#time=1305298413> uri.scheme #=> "http" uri.host #=> "foo.com" uri.path #=> "/posts" uri.query #=> "id=30&limit=5" uri.fragment #=> "time=1305298413" uri.to_s #=> "http://foo.com/posts?id=30&limit=5#time=1305298413"
module URI class RSYNC < Generic DEFAULT_PORT = 873 end register_scheme 'RSYNC', RSYNC end #=> URI::RSYNC URI.scheme_list #=> {"FILE"=>URI::File, "FTP"=>URI::FTP, "HTTP"=>URI::HTTP, # "HTTPS"=>URI::HTTPS, "LDAP"=>URI::LDAP, "LDAPS"=>URI::LDAPS, # "MAILTO"=>URI::MailTo, "RSYNC"=>URI::RSYNC} uri = URI("rsync://rsync.foo.com") #=> #<URI::RSYNC rsync://rsync.foo.com>
A good place to view an RFC spec is www.ietf.org/rfc.html.
Here is a list of all related RFC’s:
Class
tree URI::Generic
(in uri/generic.rb)
URI::File
- (in uri/file.rb)
URI::FTP
- (in uri/ftp.rb)
URI::HTTP
- (in uri/http.rb)
URI::HTTPS
- (in uri/https.rb)
URI::LDAP
- (in uri/ldap.rb)
URI::LDAPS
- (in uri/ldaps.rb)
URI::MailTo
- (in uri/mailto.rb)
URI::Parser - (in uri/common.rb)
URI::REGEXP - (in uri/common.rb)
URI::REGEXP::PATTERN - (in uri/common.rb)
URI::Util - (in uri/common.rb)
URI::Error
- (in uri/common.rb)
URI::InvalidURIError
- (in uri/common.rb)
URI::InvalidComponentError
- (in uri/common.rb)
URI::BadURIError
- (in uri/common.rb)
Akira Yamada <akira@ruby-lang.org>
Akira Yamada <akira@ruby-lang.org> Dmitry V. Sabanin <sdmitry@lrn.ru> Vincent Batts <vbatts@hashbangbash.com>
Copyright © 2001 akira yamada <akira@ruby-lang.org> You can redistribute it and/or modify it under the same term as Ruby
.
OpenURI
is an easy-to-use wrapper for Net::HTTP
, Net::HTTPS and Net::FTP.
It is possible to open an http, https or ftp URL as though it were a file:
URI.open("http://www.ruby-lang.org/") {|f| f.each_line {|line| p line} }
The opened file has several getter methods for its meta-information, as follows, since it is extended by OpenURI::Meta
.
URI.open("http://www.ruby-lang.org/en") {|f| f.each_line {|line| p line} p f.base_uri # <URI::HTTP:0x40e6ef2 URL:http://www.ruby-lang.org/en/> p f.content_type # "text/html" p f.charset # "iso-8859-1" p f.content_encoding # [] p f.last_modified # Thu Dec 05 02:45:02 UTC 2002 }
Additional header fields can be specified by an optional hash argument.
URI.open("http://www.ruby-lang.org/en/", "User-Agent" => "Ruby/#{RUBY_VERSION}", "From" => "foo@bar.invalid", "Referer" => "http://www.ruby-lang.org/") {|f| # ... }
The environment variables such as http_proxy, https_proxy and ftp_proxy are in effect by default. Here we disable proxy:
URI.open("http://www.ruby-lang.org/en/", :proxy => nil) {|f| # ... }
See OpenURI::OpenRead.open
and URI.open
for more on available options.
URI
objects can be opened in a similar way.
uri = URI.parse("http://www.ruby-lang.org/en/") uri.open {|f| # ... }
URI
objects can be read directly. The returned string is also extended by OpenURI::Meta
.
str = uri.read p str.base_uri
Tanaka Akira <akr@m17n.org>
“Parsing Ruby
is suddenly manageable!”
- You, hopefully
Here we are reopening the prism module to provide methods on nodes that aren’t templated and are meant as convenience methods.
typed: ignore
This exception is raised if the required unicode support is missing on the system. Usually this means that the iconv library is not installed.
This class is the access to openssl’s ENGINE cryptographic module implementation.
See also, www.openssl.org/docs/crypto/engine.html
Psych::Stream
is a streaming YAML
emitter. It will not buffer your YAML
, but send it straight to an IO
.
Here is an example use:
stream = Psych::Stream.new($stdout) stream.start stream.push({:foo => 'bar'}) stream.finish
YAML
will be immediately emitted to $stdout with no buffering.
Psych::Stream#start
will take a block and ensure that Psych::Stream#finish
is called, so you can do this form:
stream = Psych::Stream.new($stdout) stream.start do |em| em.push(:foo => 'bar') end
Subclass of Zlib::Error
When zlib returns a Z_STREAM_END is return if the end of the compressed data has been reached and all uncompressed out put has been produced.