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.
beginning_of_line?
(#bol?
)
Data
There are aliases to several of the methods.
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
Raised when an IO
operation fails.
File.open("/etc/hosts") {|f| f << "example"} #=> IOError: not opened for writing File.open("/etc/hosts") {|f| f.close; f.read } #=> IOError: closed stream
Note that some IO
failures raise SystemCallError
s and these are not subclasses of IOError:
File.open("does/not/exist") #=> Errno::ENOENT: No such file or directory - does/not/exist
Raised by some IO
operations when reaching the end of file. Many IO
methods exist in two forms,
one that returns nil
when the end of file is reached, the other raises EOFError
.
EOFError
is a subclass of IOError
.
file = File.open("/etc/hosts") file.read file.gets #=> nil file.readline #=> EOFError: end of file reached file.close
Class GetoptLong provides parsing both for options and for regular arguments.
Using GetoptLong, you can define options for your program. The program can then capture and respond to whatever options are included in the command that executes the program.
A simple example: file simple.rb
:
require 'getoptlong' options = GetoptLong.new( ['--number', '-n', GetoptLong::REQUIRED_ARGUMENT], ['--verbose', '-v', GetoptLong::OPTIONAL_ARGUMENT], ['--help', '-h', GetoptLong::NO_ARGUMENT] )
If you are somewhat familiar with options, you may want to skip to this full example.
A GetoptLong option has:
A string option name.
Zero or more string aliases for the name.
An option type.
Options may be defined by calling singleton method GetoptLong.new
, which returns a new GetoptLong object. Options may then be processed by calling other methods such as GetoptLong#each
.
In the array that defines an option, the first element is the string option name. Often the name takes the ‘long’ form, beginning with two hyphens.
The option name may have any number of aliases, which are defined by additional string elements.
The name and each alias must be of one of two forms:
Two hyphens, followed by one or more letters.
One hyphen, followed by a single letter.
File
aliases.rb
:
require 'getoptlong' options = GetoptLong.new( ['--xxx', '-x', '--aaa', '-a', '-p', GetoptLong::NO_ARGUMENT] ) options.each do |option, argument| p [option, argument] end
An option may be cited by its name, or by any of its aliases; the parsed option always reports the name, not an alias:
$ ruby aliases.rb -a -p --xxx --aaa -x
Output:
["--xxx", ""] ["--xxx", ""] ["--xxx", ""] ["--xxx", ""] ["--xxx", ""]
An option may also be cited by an abbreviation of its name or any alias, as long as that abbreviation is unique among the options.
File
abbrev.rb
:
require 'getoptlong' options = GetoptLong.new( ['--xxx', GetoptLong::NO_ARGUMENT], ['--xyz', GetoptLong::NO_ARGUMENT] ) options.each do |option, argument| p [option, argument] end
Command line:
$ ruby abbrev.rb --xxx --xx --xyz --xy
Output:
["--xxx", ""] ["--xxx", ""] ["--xyz", ""] ["--xyz", ""]
This command line raises GetoptLong::AmbiguousOption
:
$ ruby abbrev.rb --x
An option may be cited more than once:
$ ruby abbrev.rb --xxx --xyz --xxx --xyz
Output:
["--xxx", ""] ["--xyz", ""] ["--xxx", ""] ["--xyz", ""]
A option-like token that appears anywhere after the token --
is treated as an ordinary argument, and is not processed as an option:
$ ruby abbrev.rb --xxx --xyz -- --xxx --xyz
Output:
["--xxx", ""] ["--xyz", ""]
Each option definition includes an option type, which controls whether the option takes an argument.
File
types.rb
:
require 'getoptlong' options = GetoptLong.new( ['--xxx', GetoptLong::REQUIRED_ARGUMENT], ['--yyy', GetoptLong::OPTIONAL_ARGUMENT], ['--zzz', GetoptLong::NO_ARGUMENT] ) options.each do |option, argument| p [option, argument] end
Note that an option type has to do with the option argument (whether it is required, optional, or forbidden), not with whether the option itself is required.
An option of type GetoptLong::REQUIRED_ARGUMENT
must be followed by an argument, which is associated with that option:
$ ruby types.rb --xxx foo
Output:
["--xxx", "foo"]
If the option is not last, its argument is whatever follows it (even if the argument looks like another option):
$ ruby types.rb --xxx --yyy
Output:
["--xxx", "--yyy"]
If the option is last, an exception is raised:
$ ruby types.rb # Raises GetoptLong::MissingArgument
An option of type GetoptLong::OPTIONAL_ARGUMENT
may be followed by an argument, which if given is associated with that option.
If the option is last, it does not have an argument:
$ ruby types.rb --yyy
Output:
["--yyy", ""]
If the option is followed by another option, it does not have an argument:
$ ruby types.rb --yyy --zzz
Output:
["--yyy", ""] ["--zzz", ""]
Otherwise the option is followed by its argument, which is associated with that option:
$ ruby types.rb --yyy foo
Output:
["--yyy", "foo"]
An option of type GetoptLong::NO_ARGUMENT
takes no argument:
ruby types.rb --zzz foo
Output:
["--zzz", ""]
You can process options either with method each
and a block, or with method get
.
During processing, each found option is removed, along with its argument if there is one. After processing, each remaining element was neither an option nor the argument for an option.
File
argv.rb
:
require 'getoptlong' options = GetoptLong.new( ['--xxx', GetoptLong::REQUIRED_ARGUMENT], ['--yyy', GetoptLong::OPTIONAL_ARGUMENT], ['--zzz', GetoptLong::NO_ARGUMENT] ) puts "Original ARGV: #{ARGV}" options.each do |option, argument| p [option, argument] end puts "Remaining ARGV: #{ARGV}"
Command line:
$ ruby argv.rb --xxx Foo --yyy Bar Baz --zzz Bat Bam
Output:
Original ARGV: ["--xxx", "Foo", "--yyy", "Bar", "Baz", "--zzz", "Bat", "Bam"] ["--xxx", "Foo"] ["--yyy", "Bar"] ["--zzz", ""] Remaining ARGV: ["Baz", "Bat", "Bam"]
There are three settings that control the way the options are interpreted:
PERMUTE
.
REQUIRE_ORDER
.
RETURN_IN_ORDER
.
The initial setting for a new GetoptLong object is REQUIRE_ORDER
if environment variable POSIXLY_CORRECT
is defined, PERMUTE
otherwise.
In the PERMUTE
ordering, options and other, non-option, arguments may appear in any order and any mixture.
File
permute.rb
:
require 'getoptlong' options = GetoptLong.new( ['--xxx', GetoptLong::REQUIRED_ARGUMENT], ['--yyy', GetoptLong::OPTIONAL_ARGUMENT], ['--zzz', GetoptLong::NO_ARGUMENT] ) puts "Original ARGV: #{ARGV}" options.each do |option, argument| p [option, argument] end puts "Remaining ARGV: #{ARGV}"
Command line:
$ ruby permute.rb Foo --zzz Bar --xxx Baz --yyy Bat Bam --xxx Bag Bah
Output:
Original ARGV: ["Foo", "--zzz", "Bar", "--xxx", "Baz", "--yyy", "Bat", "Bam", "--xxx", "Bag", "Bah"] ["--zzz", ""] ["--xxx", "Baz"] ["--yyy", "Bat"] ["--xxx", "Bag"] Remaining ARGV: ["Foo", "Bar", "Bam", "Bah"]
In the REQUIRE_ORDER
ordering, all options precede all non-options; that is, each word after the first non-option word is treated as a non-option word (even if it begins with a hyphen).
File
require_order.rb
:
require 'getoptlong' options = GetoptLong.new( ['--xxx', GetoptLong::REQUIRED_ARGUMENT], ['--yyy', GetoptLong::OPTIONAL_ARGUMENT], ['--zzz', GetoptLong::NO_ARGUMENT] ) options.ordering = GetoptLong::REQUIRE_ORDER puts "Original ARGV: #{ARGV}" options.each do |option, argument| p [option, argument] end puts "Remaining ARGV: #{ARGV}"
Command line:
$ ruby require_order.rb --xxx Foo Bar --xxx Baz --yyy Bat -zzz
Output:
Original ARGV: ["--xxx", "Foo", "Bar", "--xxx", "Baz", "--yyy", "Bat", "-zzz"] ["--xxx", "Foo"] Remaining ARGV: ["Bar", "--xxx", "Baz", "--yyy", "Bat", "-zzz"]
In the RETURN_IN_ORDER
ordering, every word is treated as an option. A word that begins with a hyphen (or two) is treated in the usual way; a word word
that does not so begin is treated as an option whose name is an empty string, and whose value is word
.
File
return_in_order.rb
:
require 'getoptlong' options = GetoptLong.new( ['--xxx', GetoptLong::REQUIRED_ARGUMENT], ['--yyy', GetoptLong::OPTIONAL_ARGUMENT], ['--zzz', GetoptLong::NO_ARGUMENT] ) options.ordering = GetoptLong::RETURN_IN_ORDER puts "Original ARGV: #{ARGV}" options.each do |option, argument| p [option, argument] end puts "Remaining ARGV: #{ARGV}"
Command line:
$ ruby return_in_order.rb Foo --xxx Bar Baz --zzz Bat Bam
Output:
Original ARGV: ["Foo", "--xxx", "Bar", "Baz", "--zzz", "Bat", "Bam"] ["", "Foo"] ["--xxx", "Bar"] ["", "Baz"] ["--zzz", ""] ["", "Bat"] ["", "Bam"] Remaining ARGV: []
File
fibonacci.rb
:
require 'getoptlong' options = GetoptLong.new( ['--number', '-n', GetoptLong::REQUIRED_ARGUMENT], ['--verbose', '-v', GetoptLong::OPTIONAL_ARGUMENT], ['--help', '-h', GetoptLong::NO_ARGUMENT] ) def help(status = 0) puts <<~HELP Usage: -n n, --number n: Compute Fibonacci number for n. -v [boolean], --verbose [boolean]: Show intermediate results; default is 'false'. -h, --help: Show this help. HELP exit(status) end def print_fibonacci (number) return 0 if number == 0 return 1 if number == 1 or number == 2 i = 0 j = 1 (2..number).each do k = i + j i = j j = k puts j if @verbose end puts j unless @verbose end options.each do |option, argument| case option when '--number' @number = argument.to_i when '--verbose' @verbose = if argument.empty? true elsif argument.match(/true/i) true elsif argument.match(/false/i) false else puts '--verbose argument must be true or false' help(255) end when '--help' help end end unless @number puts 'Option --number is required.' help(255) end print_fibonacci(@number)
Command line:
$ ruby fibonacci.rb
Output:
Option --number is required. Usage: -n n, --number n: Compute Fibonacci number for n. -v [boolean], --verbose [boolean]: Show intermediate results; default is 'false'. -h, --help: Show this help.
Command line:
$ ruby fibonacci.rb --number
Raises GetoptLong::MissingArgument
:
fibonacci.rb: option `--number' requires an argument
Command line:
$ ruby fibonacci.rb --number 6
Output:
8
Command line:
$ ruby fibonacci.rb --number 6 --verbose
Output:
1 2 3 5 8
Command line:
$ ruby fibonacci.rb –number 6 –verbose yes
Output:
--verbose argument must be true or false Usage: -n n, --number n: Compute Fibonacci number for n. -v [boolean], --verbose [boolean]: Show intermediate results; default is 'false'. -h, --help: Show this help.
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, www.st.cs.uni-sb.de/~lindig/papers/#pretty
Philip Wadler, A prettier printer, March 1998, homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier
Tanaka Akira <akr@fsij.org>
Resolv
is a thread-aware DNS
resolver library written in Ruby. Resolv
can handle multiple DNS
requests concurrently without blocking the entire Ruby interpreter.
See also resolv-replace.rb to replace the libc resolver with Resolv
.
Resolv
can look up various DNS
resources using the DNS
module directly.
Examples:
p Resolv.getaddress "www.ruby-lang.org" p Resolv.getname "210.251.121.214" Resolv::DNS.open do |dns| ress = dns.getresources "www.ruby-lang.org", Resolv::DNS::Resource::IN::A p ress.map(&:address) ress = dns.getresources "ruby-lang.org", Resolv::DNS::Resource::IN::MX p ress.map { |r| [r.exchange.to_s, r.preference] } end
NIS is not supported.
/etc/nsswitch.conf is not supported.
Weak Reference class that allows a referenced object to be garbage-collected.
A WeakRef
may be used exactly like the object it references.
Usage:
foo = Object.new # create a new object instance p foo.to_s # original's class foo = WeakRef.new(foo) # reassign foo with WeakRef instance p foo.to_s # should be same class GC.start # start the garbage collector p foo.to_s # should raise exception (recycled)
Raised when attempting to divide an integer by 0.
42 / 0 #=> ZeroDivisionError: divided by 0
Note that only division by an exact 0 will raise the exception:
42 / 0.0 #=> Float::INFINITY 42 / -0.0 #=> -Float::INFINITY 0 / 0.0 #=> NaN
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
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
ThreadGroup
provides a means of keeping track of a number of threads as a group.
A given Thread
object can only belong to one ThreadGroup
at a time; adding a thread to a new group will remove it from any previous group.
Newly created threads belong to the same group as the thread from which they were created.
Threads are the Ruby implementation for a concurrent programming model.
Programs that require multiple threads of execution are a perfect candidate for Ruby’s Thread
class.
For example, we can create a new thread separate from the main thread’s execution using ::new
.
thr = Thread.new { puts "What's the big deal" }
Then we are able to pause the execution of the main thread and allow our new thread to finish, using join
:
thr.join #=> "What's the big deal"
If we don’t call thr.join
before the main thread terminates, then all other threads including thr
will be killed.
Alternatively, you can use an array for handling multiple threads at once, like in the following example:
threads = [] threads << Thread.new { puts "What's the big deal" } threads << Thread.new { 3.times { puts "Threads are fun!" } }
After creating a few threads we wait for them all to finish consecutively.
threads.each { |thr| thr.join }
To retrieve the last value of a thread, use value
thr = Thread.new { sleep 1; "Useful value" } thr.value #=> "Useful value"
Thread
initialization In order to create new threads, Ruby provides ::new
, ::start
, and ::fork
. A block must be provided with each of these methods, otherwise a ThreadError
will be raised.
When subclassing the Thread
class, the initialize
method of your subclass will be ignored by ::start
and ::fork
. Otherwise, be sure to call super in your initialize
method.
Thread
termination For terminating threads, Ruby provides a variety of ways to do this.
The class method ::kill
, is meant to exit a given thread:
thr = Thread.new { sleep } Thread.kill(thr) # sends exit() to thr
Alternatively, you can use the instance method exit
, or any of its aliases kill
or terminate
.
thr.exit
Thread
status Ruby provides a few instance methods for querying the state of a given thread. To get a string with the current thread’s state use status
thr = Thread.new { sleep } thr.status # => "sleep" thr.exit thr.status # => false
You can also use alive?
to tell if the thread is running or sleeping, and stop?
if the thread is dead or sleeping.
Thread
variables and scope Since threads are created with blocks, the same rules apply to other Ruby blocks for variable scope. Any local variables created within this block are accessible to only this thread.
Each fiber has its own bucket for Thread#[]
storage. When you set a new fiber-local it is only accessible within this Fiber
. To illustrate:
Thread.new { Thread.current[:foo] = "bar" Fiber.new { p Thread.current[:foo] # => nil }.resume }.join
This example uses []
for getting and []=
for setting fiber-locals, you can also use keys
to list the fiber-locals for a given thread and key?
to check if a fiber-local exists.
When it comes to thread-locals, they are accessible within the entire scope of the thread. Given the following example:
Thread.new{ Thread.current.thread_variable_set(:foo, 1) p Thread.current.thread_variable_get(:foo) # => 1 Fiber.new{ Thread.current.thread_variable_set(:foo, 2) p Thread.current.thread_variable_get(:foo) # => 2 }.resume p Thread.current.thread_variable_get(:foo) # => 2 }.join
You can see that the thread-local :foo
carried over into the fiber and was changed to 2
by the end of the thread.
This example makes use of thread_variable_set
to create new thread-locals, and thread_variable_get
to reference them.
There is also thread_variables
to list all thread-locals, and thread_variable?
to check if a given thread-local exists.
Exception
handling When an unhandled exception is raised inside a thread, it will terminate. By default, this exception will not propagate to other threads. The exception is stored and when another thread calls value
or join
, the exception will be re-raised in that thread.
t = Thread.new{ raise 'something went wrong' } t.value #=> RuntimeError: something went wrong
An exception can be raised from outside the thread using the Thread#raise
instance method, which takes the same parameters as Kernel#raise
.
Setting Thread.abort_on_exception
= true, Thread#abort_on_exception
= true, or $DEBUG = true will cause a subsequent unhandled exception raised in a thread to be automatically re-raised in the main thread.
With the addition of the class method ::handle_interrupt
, you can now handle exceptions asynchronously with threads.
Ruby provides a few ways to support scheduling threads in your program.
The first way is by using the class method ::stop
, to put the current running thread to sleep and schedule the execution of another thread.
Once a thread is asleep, you can use the instance method wakeup
to mark your thread as eligible for scheduling.
You can also try ::pass
, which attempts to pass execution to another thread but is dependent on the OS whether a running thread will switch or not. The same goes for priority
, which lets you hint to the thread scheduler which threads you want to take precedence when passing execution. This method is also dependent on the OS and may be ignored on some platforms.
The exception class which will be raised when pushing into a closed Queue. See Thread::Queue#close
and Thread::SizedQueue#close
.
Raised when throw
is called with a tag which does not have corresponding catch
block.
throw "foo", "bar"
raises the exception:
UncaughtThrowError: uncaught throw "foo"
newton.rb
Solves the nonlinear algebraic equation system f = 0 by Newton’s method. This program is not dependent on BigDecimal
.
To call:
n = nlsolve(f,x) where n is the number of iterations required, x is the initial value vector f is an Object which is used to compute the values of the equations to be solved.
It must provide the following methods:
returns the values of all functions at x
returns 0.0
returns 1.0
returns 2.0
returns 10.0
returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal.
On exit, x is the solution vector.
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.
Psych
is a YAML
parser and emitter. Psych
leverages libyaml [Home page: pyyaml.org/wiki/LibYAML] or [git repo: github.com/yaml/libyaml] for its YAML
parsing and emitting capabilities. In addition to wrapping libyaml, Psych
also knows how to serialize and de-serialize most Ruby objects to and from the YAML
format.
YAML
RIGHT NOW! # Parse some YAML Psych.load("--- foo") # => "foo" # Emit some YAML Psych.dump("foo") # => "--- foo\n...\n" { :a => 'b'}.to_yaml # => "---\n:a: b\n"
Got more time on your hands? Keep on reading!
YAML
Parsing Psych
provides a range of interfaces for parsing a YAML
document ranging from low level to high level, depending on your parsing needs. At the lowest level, is an event based parser. Mid level is access to the raw YAML
AST, and at the highest level is the ability to unmarshal YAML
to Ruby objects.
YAML
Emitting Psych
provides a range of interfaces ranging from low to high level for producing YAML
documents. Very similar to the YAML
parsing interfaces, Psych
provides at the lowest level, an event based system, mid-level is building a YAML
AST, and the highest level is converting a Ruby object straight to a YAML
document.
The high level YAML
parser provided by Psych
simply takes YAML
as input and returns a Ruby data structure. For information on using the high level parser see Psych.load
Psych.safe_load("--- a") # => 'a' Psych.safe_load("---\n - a\n - b") # => ['a', 'b'] # From a trusted string: Psych.load("--- !ruby/range\nbegin: 0\nend: 42\nexcl: false\n") # => 0..42
Psych.safe_load_file("data.yml", permitted_classes: [Date]) Psych.load_file("trusted_database.yml")
Exception
handling begin # The second argument changes only the exception contents Psych.parse("--- `", "file.txt") rescue Psych::SyntaxError => ex ex.file # => 'file.txt' ex.message # => "(file.txt): found character that cannot start any token" end
The high level emitter has the easiest interface. Psych
simply takes a Ruby data structure and converts it to a YAML
document. See Psych.dump
for more information on dumping a Ruby data structure.
# Dump an array, get back a YAML string Psych.dump(['a', 'b']) # => "---\n- a\n- b\n" # Dump an array to an IO object Psych.dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890> # Dump an array with indentation set Psych.dump(['a', ['b']], :indentation => 3) # => "---\n- a\n- - b\n" # Dump an array to an IO with indentation set Psych.dump(['a', ['b']], StringIO.new, :indentation => 3)
Currently there is no direct API for dumping Ruby structure to file:
File.open('database.yml', 'w') do |file| file.write(Psych.dump(['a', 'b'])) end
Psych
provides access to an AST produced from parsing a YAML
document. This tree is built using the Psych::Parser
and Psych::TreeBuilder
. The AST can be examined and manipulated freely. Please see Psych::parse_stream
, Psych::Nodes
, and Psych::Nodes::Node
for more information on dealing with YAML
syntax trees.
# Returns Psych::Nodes::Stream Psych.parse_stream("---\n - a\n - b") # Returns Psych::Nodes::Document Psych.parse("---\n - a\n - b")
# Returns Psych::Nodes::Stream Psych.parse_stream(File.read('database.yml')) # Returns Psych::Nodes::Document Psych.parse_file('database.yml')
Exception
handling begin # The second argument changes only the exception contents Psych.parse("--- `", "file.txt") rescue Psych::SyntaxError => ex ex.file # => 'file.txt' ex.message # => "(file.txt): found character that cannot start any token" end
At the mid level is building an AST. This AST is exactly the same as the AST used when parsing a YAML
document. Users can build an AST by hand and the AST knows how to emit itself as a YAML
document. See Psych::Nodes
, Psych::Nodes::Node
, and Psych::TreeBuilder
for more information on building a YAML
AST.
# We need Psych::Nodes::Stream (not Psych::Nodes::Document) stream = Psych.parse_stream("---\n - a\n - b") stream.to_yaml # => "---\n- a\n- b\n"
# We need Psych::Nodes::Stream (not Psych::Nodes::Document) stream = Psych.parse_stream(File.read('database.yml')) File.open('database.yml', 'w') do |file| file.write(stream.to_yaml) end
The lowest level parser should be used when the YAML
input is already known, and the developer does not want to pay the price of building an AST or automatic detection and conversion to Ruby objects. See Psych::Parser
for more information on using the event based parser.
Psych::Nodes::Stream
structure parser = Psych::Parser.new(TreeBuilder.new) # => #<Psych::Parser> parser = Psych.parser # it's an alias for the above parser.parse("---\n - a\n - b") # => #<Psych::Parser> parser.handler # => #<Psych::TreeBuilder> parser.handler.root # => #<Psych::Nodes::Stream>
recorder = Psych::Handlers::Recorder.new parser = Psych::Parser.new(recorder) parser.parse("---\n - a\n - b") recorder.events # => [list of [event, args] lists] # event is one of: Psych::Handler::EVENTS # args are the arguments passed to the event
The lowest level emitter is an event based system. Events are sent to a Psych::Emitter
object. That object knows how to convert the events to a YAML
document. This interface should be used when document format is known in advance or speed is a concern. See Psych::Emitter
for more information.
Psych.parser.parse("--- a") # => #<Psych::Parser> parser.handler.first # => #<Psych::Nodes::Stream> parser.handler.first.to_ruby # => ["a"] parser.handler.root.first # => #<Psych::Nodes::Document> parser.handler.root.first.to_ruby # => "a" # You can instantiate an Emitter manually Psych::Visitors::ToRuby.new.accept(parser.handler.root.first) # => "a"
The Readline
module provides interface for GNU Readline
. This module defines a number of methods to facilitate completion and accesses input history from the Ruby interpreter. This module supported Edit Line(libedit) too. libedit is compatible with GNU Readline
.
Reads one inputted line with line edit by Readline.readline
method. At this time, the facilitatation completion and the key bind like Emacs can be operated like GNU Readline
.
require "readline" while buf = Readline.readline("> ", true) p buf end
The content that the user input can be recorded to the history. The history can be accessed by Readline::HISTORY
constant.
require "readline" while buf = Readline.readline("> ", true) p Readline::HISTORY.to_a print("-> ", buf, "\n") end
Documented by Kouji Takao <kouji dot takao at gmail dot com>.
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).
Calculates the set of unambiguous abbreviations for a given set of strings.
require 'abbrev' require 'pp' pp Abbrev.abbrev(['ruby']) #=> {"ruby"=>"ruby", "rub"=>"ruby", "ru"=>"ruby", "r"=>"ruby"} pp Abbrev.abbrev(%w{ ruby rules })
Generates:
{ "ruby" => "ruby", "rub" => "ruby", "rules" => "rules", "rule" => "rules", "rul" => "rules" }
It also provides an array core extension, Array#abbrev
.
pp %w{ summer winter }.abbrev
Generates:
{ "summer" => "summer", "summe" => "summer", "summ" => "summer", "sum" => "summer", "su" => "summer", "s" => "summer", "winter" => "winter", "winte" => "winter", "wint" => "winter", "win" => "winter", "wi" => "winter", "w" => "winter" }
The Forwardable
module provides delegation of specified methods to a designated object, using the methods def_delegator
and def_delegators
.
For example, say you have a class RecordCollection which contains an array @records
. You could provide the lookup method record_number(), which simply calls [] on the @records
array, like this:
require 'forwardable' class RecordCollection attr_accessor :records extend Forwardable def_delegator :@records, :[], :record_number end
We can use the lookup method like so:
r = RecordCollection.new r.records = [4,5,6] r.record_number(0) # => 4
Further, if you wish to provide the methods size, <<, and map, all of which delegate to @records, this is how you can do it:
class RecordCollection # re-open RecordCollection class def_delegators :@records, :size, :<<, :map end r = RecordCollection.new r.records = [1,2,3] r.record_number(0) # => 1 r.size # => 3 r << 4 # => [1, 2, 3, 4] r.map { |x| x * 2 } # => [2, 4, 6, 8]
You can even extend regular objects with Forwardable
.
my_hash = Hash.new my_hash.extend Forwardable # prepare object for delegation my_hash.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts() my_hash.puts "Howdy!"
You could use Forwardable
as an alternative to inheritance, when you don’t want to inherit all methods from the superclass. For instance, here is how you might add a range of Array
instance methods to a new class Queue
:
class Queue extend Forwardable def initialize @q = [ ] # prepare delegate object end # setup preferred interface, enq() and deq()... def_delegator :@q, :push, :enq def_delegator :@q, :shift, :deq # support some general Array methods that fit Queues well def_delegators :@q, :clear, :first, :push, :shift, :size end q = Thread::Queue.new q.enq 1, 2, 3, 4, 5 q.push 6 q.shift # => 1 while q.size > 0 puts q.deq end q.enq "Ruby", "Perl", "Python" puts q.first q.clear puts q.first
This should output:
2 3 4 5 6 Ruby nil
Be advised, RDoc
will not detect delegated methods.
forwardable.rb
provides single-method delegation via the def_delegator
and def_delegators
methods. For full-class delegation via DelegateClass, see delegate.rb
.