Raised to stop the iteration, in particular by Enumerator#next
. It is rescued by Kernel#loop
.
loop do puts "Hello" raise StopIteration puts "World" end puts "Done!"
produces:
Hello Done!
Raised by exit
to initiate the termination of the script.
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
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
The Addrinfo
class maps struct addrinfo
to ruby. This structure identifies an Internet host and a service.
IPAddr
provides a set of methods to manipulate an IP address. Both IPv4 and IPv6 are supported.
require 'ipaddr' ipaddr1 = IPAddr.new "3ffe:505:2::1" p ipaddr1 #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff> p ipaddr1.to_s #=> "3ffe:505:2::1" ipaddr2 = ipaddr1.mask(48) #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000> p ipaddr2.to_s #=> "3ffe:505:2::" ipaddr3 = IPAddr.new "192.168.2.0/24" p ipaddr3 #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>
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:
newline object and space generation block for PrettyPrint.new
optional width argument for PrettyPrint#text
There are several candidate uses:
text formatting using proportional fonts
multibyte characters which has columns different to number of bytes
non-string formatting
Box based formatting?
Other (better) model/algorithm?
Report any bugs at bugs.ruby-lang.org
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
Tanaka Akira <akr@fsij.org>
PStore implements a file based persistence mechanism based on a Hash
. User code can store hierarchies of Ruby objects (values) into the data store by name (keys). An object hierarchy may be just a single object. User code may later read values back from the data store or even update data, as needed.
The transactional behavior ensures that any changes succeed or fail together. This can be used to ensure that the data store is not left in a transitory state, where some values were updated but others were not.
Behind the scenes, Ruby objects are stored to the data store file with Marshal
. That carries the usual limitations. Proc
objects cannot be marshalled, for example.
There are three important concepts here (details at the links):
Store: a store is an instance of PStore.
Entries: the store is hash-like; each entry is the key for a stored object.
Transactions: each transaction is a collection of prospective changes to the store; a transaction is defined in the block given with a call to PStore#transaction
.
Examples on this page need a store that has known properties. They can get a new (and populated) store by calling thus:
example_store do |store| # Example code using store goes here. end
All we really need to know about example_store
is that it yields a fresh store with a known population of entries; its implementation:
require 'pstore' require 'tempfile' # Yield a pristine store for use in examples. def example_store # Create the store in a temporary file. Tempfile.create do |file| store = PStore.new(file) # Populate the store. store.transaction do store[:foo] = 0 store[:bar] = 1 store[:baz] = 2 end yield store end end
The contents of the store are maintained in a file whose path is specified when the store is created (see PStore.new
). The objects are stored and retrieved using module Marshal
, which means that certain objects cannot be added to the store; see Marshal::dump.
A store may have any number of entries. Each entry has a key and a value, just as in a hash:
Key: as in a hash, the key can be (almost) any object; see Hash Keys. You may find it convenient to keep it simple by using only symbols or strings as keys.
Value: the value may be any object that can be marshalled by Marshal (see Marshal::dump) and in fact may be a collection (e.g., an array, a hash, a set, a range, etc). That collection may in turn contain nested objects, including collections, to any depth; those objects must also be Marshal-able. See Hierarchical Values.
The block given with a call to method transaction
# contains a transaction, which consists of calls to PStore methods that read from or write to the store (that is, all PStore methods except transaction
itself, path
, and Pstore.new):
example_store do |store| store.transaction do store.keys # => [:foo, :bar, :baz] store[:bat] = 3 store.keys # => [:foo, :bar, :baz, :bat] end end
Execution of the transaction is deferred until the block exits, and is executed atomically (all-or-nothing): either all transaction calls are executed, or none are. This maintains the integrity of the store.
Other code in the block (including even calls to path
and PStore.new
) is executed immediately, not deferred.
The transaction block:
May not contain a nested call to transaction
.
Is the only context where methods that read from or write to the store are allowed.
As seen above, changes in a transaction are made automatically when the block exits. The block may be exited early by calling method commit
or abort
.
Method
commit
triggers the update to the store and exits the block:
example_store do |store| store.transaction do store.keys # => [:foo, :bar, :baz] store[:bat] = 3 store.commit fail 'Cannot get here' end store.transaction do # Update was completed. store.keys # => [:foo, :bar, :baz, :bat] end end
Method
abort
discards the update to the store and exits the block:
example_store do |store| store.transaction do store.keys # => [:foo, :bar, :baz] store[:bat] = 3 store.abort fail 'Cannot get here' end store.transaction do # Update was not completed. store.keys # => [:foo, :bar, :baz] end end
By default, a transaction allows both reading from and writing to the store:
store.transaction do # Read-write transaction. # Any code except a call to #transaction is allowed here. end
If argument read_only
is passed as true
, only reading is allowed:
store.transaction(true) do # Read-only transaction: # Calls to #transaction, #[]=, and #delete are not allowed here. end
The value for an entry may be a simple object (as seen above). It may also be a hierarchy of objects nested to any depth:
deep_store = PStore.new('deep.store') deep_store.transaction do array_of_hashes = [{}, {}, {}] deep_store[:array_of_hashes] = array_of_hashes deep_store[:array_of_hashes] # => [{}, {}, {}] hash_of_arrays = {foo: [], bar: [], baz: []} deep_store[:hash_of_arrays] = hash_of_arrays deep_store[:hash_of_arrays] # => {:foo=>[], :bar=>[], :baz=>[]} deep_store[:hash_of_arrays][:foo].push(:bat) deep_store[:hash_of_arrays] # => {:foo=>[:bat], :bar=>[], :baz=>[]} end
And recall that you can use dig methods in a returned hierarchy of objects.
Use method PStore.new
to create a store. The new store creates or opens its containing file:
store = PStore.new('t.store')
Use method []=
to update or create an entry:
example_store do |store| store.transaction do store[:foo] = 1 # Update. store[:bam] = 1 # Create. end end
Use method delete
to remove an entry:
example_store do |store| store.transaction do store.delete(:foo) store[:foo] # => nil end end
Use method fetch
(allows default) or []
(defaults to nil
) to retrieve an entry:
example_store do |store| store.transaction do store[:foo] # => 0 store[:nope] # => nil store.fetch(:baz) # => 2 store.fetch(:nope, nil) # => nil store.fetch(:nope) # Raises exception. end end
Use method key?
to determine whether a given key exists:
example_store do |store| store.transaction do store.key?(:foo) # => true end end
Use method keys
to retrieve keys:
example_store do |store| store.transaction do store.keys # => [:foo, :bar, :baz] end end
Use method path
to retrieve the path to the store’s underlying file; this method may be called from outside a transaction block:
store = PStore.new('t.store') store.path # => "t.store"
For transaction safety, see:
Optional argument thread_safe
at method PStore.new
.
Attribute ultra_safe
.
Needless to say, if you’re storing valuable data with PStore, then you should backup the PStore file from time to time.
require "pstore" # A mock wiki object. class WikiPage attr_reader :page_name def initialize(page_name, author, contents) @page_name = page_name @revisions = Array.new add_revision(author, contents) end def add_revision(author, contents) @revisions << {created: Time.now, author: author, contents: contents} end def wiki_page_references [@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+[a-z]+){2,}/) end end # Create a new wiki page. home_page = WikiPage.new("HomePage", "James Edward Gray II", "A page about the JoysOfDocumentation..." ) wiki = PStore.new("wiki_pages.pstore") # Update page data and the index together, or not at all. wiki.transaction do # Store page. wiki[home_page.page_name] = home_page # Create page index. wiki[:wiki_index] ||= Array.new # Update wiki index. wiki[:wiki_index].push(*home_page.wiki_page_references) end # Read wiki data, setting argument read_only to true. wiki.transaction(true) do wiki.keys.each do |key| puts key puts wiki[key] end end
The class of the singleton object true
.
Several of its methods act as operators:
One other method:
A class that provides the functionality of Kernel#set_trace_func
in a nice Object-Oriented API.
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>]
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
)
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:
SHA512
SHA384
SHA256
The latest versions of the FIPS publications can be found here: csrc.nist.gov/publications/PubsFIPS.html.
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).
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>
The Prism
Ruby parser.
“Parsing Ruby is suddenly manageable!”
- You, hopefully
This file is generated by the templates/template.rb script and should not be modified manually. See templates/lib/prism/compiler.rb.erb if you are looking to modify the template
This file is generated by the templates/template.rb script and should not be modified manually. See templates/lib/prism/dispatcher.rb.erb if you are looking to modify the template
This file is generated by the templates/template.rb script and should not be modified manually. See templates/lib/prism/dsl.rb.erb if you are looking to modify the template
This file is generated by the templates/template.rb script and should not be modified manually. See templates/lib/prism/mutation_compiler.rb.erb if you are looking to modify the template
This file is generated by the templates/template.rb script and should not be modified manually. See templates/lib/prism/node.rb.erb if you are looking to modify the template
Here we are reopening the prism module to provide methods on nodes that aren’t templated and are meant as convenience methods.
This file is generated by the templates/template.rb script and should not be modified manually. See templates/lib/prism/visitor.rb.erb if you are looking to modify the template
A module to implement the Linda distributed computing paradigm in Ruby.
See the sample/drb/ directory in the Ruby distribution, from 1.8.2 onwards.
A base class for objects representing a C structure
Wrapper for arrays within a struct
A pointer to a C structure
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