The Matrix
class represents a mathematical matrix. It provides methods for creating matrices, operating on them arithmetically and algebraically, and determining their mathematical properties such as trace, rank, inverse, determinant, or eigensystem.
OptionParser
OptionParser
is a class for command-line option analysis. It is much more advanced, yet also easier to use, than GetoptLong
, and is a more Ruby-oriented solution.
The argument specification and the code to handle it are written in the same place.
It can output an option summary; you don’t need to maintain this string separately.
Optional and mandatory arguments are specified very gracefully.
Arguments can be automatically converted to a specified class.
Arguments can be restricted to a certain set.
All of these features are demonstrated in the examples below. See make_switch
for full documentation.
require 'optparse' options = {} OptionParser.new do |opts| opts.banner = "Usage: example.rb [options]" opts.on("-v", "--[no-]verbose", "Run verbosely") do |v| options[:verbose] = v end end.parse! p options p ARGV
OptionParser
can be used to automatically generate help for the commands you write:
require 'optparse' Options = Struct.new(:name) class Parser def self.parse(options) args = Options.new("world") opt_parser = OptionParser.new do |opts| opts.banner = "Usage: example.rb [options]" opts.on("-nNAME", "--name=NAME", "Name to say hello to") do |n| args.name = n end opts.on("-h", "--help", "Prints this help") do puts opts exit end end opt_parser.parse!(options) return args end end options = Parser.parse %w[--help] #=> # Usage: example.rb [options] # -n, --name=NAME Name to say hello to # -h, --help Prints this help
For options that require an argument, option specification strings may include an option name in all caps. If an option is used without the required argument, an exception will be raised.
require 'optparse' options = {} OptionParser.new do |parser| parser.on("-r", "--require LIBRARY", "Require the LIBRARY before executing your script") do |lib| puts "You required #{lib}!" end end.parse!
Used:
$ ruby optparse-test.rb -r optparse-test.rb:9:in `<main>': missing argument: -r (OptionParser::MissingArgument) $ ruby optparse-test.rb -r my-library You required my-library!
OptionParser
supports the ability to coerce command line arguments into objects for us.
OptionParser
comes with a few ready-to-use kinds of type coercion. They are:
Date
– Anything accepted by Date.parse
DateTime
– Anything accepted by DateTime.parse
Time
– Anything accepted by Time.httpdate
or Time.parse
URI
– Anything accepted by URI.parse
Shellwords
– Anything accepted by Shellwords.shellwords
String
– Any non-empty string
Integer
– Any integer. Will convert octal. (e.g. 124, -3, 040)
Float
– Any float. (e.g. 10, 3.14, -100E+13)
Numeric
– Any integer, float, or rational (1, 3.4, 1/3)
DecimalInteger
– Like Integer
, but no octal format.
OctalInteger
– Like Integer
, but no decimal format.
DecimalNumeric
– Decimal integer or float.
TrueClass
– Accepts ‘+, yes, true, -, no, false’ and defaults as true
FalseClass
– Same as TrueClass
, but defaults to false
Array
– Strings separated by ‘,’ (e.g. 1,2,3)
Regexp
– Regular expressions. Also includes options.
We can also add our own coercions, which we will cover soon.
As an example, the built-in Time
conversion is used. The other built-in conversions behave in the same way. OptionParser
will attempt to parse the argument as a Time
. If it succeeds, that time will be passed to the handler block. Otherwise, an exception will be raised.
require 'optparse' require 'optparse/time' OptionParser.new do |parser| parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time| p time end end.parse!
Used:
$ ruby optparse-test.rb -t nonsense ... invalid argument: -t nonsense (OptionParser::InvalidArgument) $ ruby optparse-test.rb -t 10-11-12 2010-11-12 00:00:00 -0500 $ ruby optparse-test.rb -t 9:30 2014-08-13 09:30:00 -0400
The accept
method on OptionParser
may be used to create converters. It specifies which conversion block to call whenever a class is specified. The example below uses it to fetch a User
object before the on
handler receives it.
require 'optparse' User = Struct.new(:id, :name) def find_user id not_found = ->{ raise "No User Found for id #{id}" } [ User.new(1, "Sam"), User.new(2, "Gandalf") ].find(not_found) do |u| u.id == id end end op = OptionParser.new op.accept(User) do |user_id| find_user user_id.to_i end op.on("--user ID", User) do |user| puts user end op.parse!
Used:
$ ruby optparse-test.rb --user 1 #<struct User id=1, name="Sam"> $ ruby optparse-test.rb --user 2 #<struct User id=2, name="Gandalf"> $ ruby optparse-test.rb --user 3 optparse-test.rb:15:in `block in find_user': No User Found for id 3 (RuntimeError)
Hash
The into
option of order
, parse
and so on methods stores command line options into a Hash
.
require 'optparse' params = {} OptionParser.new do |opts| opts.on('-a') opts.on('-b NUM', Integer) opts.on('-v', '--verbose') end.parse!(into: params) p params
Used:
$ ruby optparse-test.rb -a {:a=>true} $ ruby optparse-test.rb -a -v {:a=>true, :verbose=>true} $ ruby optparse-test.rb -a -b 100 {:a=>true, :b=>100}
The following example is a complete Ruby program. You can run it and see the effect of specifying various options. This is probably the best way to learn the features of optparse
.
require 'optparse' require 'optparse/time' require 'ostruct' require 'pp' class OptparseExample Version = '1.0.0' CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary] CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" } class ScriptOptions attr_accessor :library, :inplace, :encoding, :transfer_type, :verbose, :extension, :delay, :time, :record_separator, :list def initialize self.library = [] self.inplace = false self.encoding = "utf8" self.transfer_type = :auto self.verbose = false end def define_options(parser) parser.banner = "Usage: example.rb [options]" parser.separator "" parser.separator "Specific options:" # add additional options perform_inplace_option(parser) delay_execution_option(parser) execute_at_time_option(parser) specify_record_separator_option(parser) list_example_option(parser) specify_encoding_option(parser) optional_option_argument_with_keyword_completion_option(parser) boolean_verbose_option(parser) parser.separator "" parser.separator "Common options:" # No argument, shows at tail. This will print an options summary. # Try it and see! parser.on_tail("-h", "--help", "Show this message") do puts parser exit end # Another typical switch to print the version. parser.on_tail("--version", "Show version") do puts Version exit end end def perform_inplace_option(parser) # Specifies an optional option argument parser.on("-i", "--inplace [EXTENSION]", "Edit ARGV files in place", "(make backup if EXTENSION supplied)") do |ext| self.inplace = true self.extension = ext || '' self.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot. end end def delay_execution_option(parser) # Cast 'delay' argument to a Float. parser.on("--delay N", Float, "Delay N seconds before executing") do |n| self.delay = n end end def execute_at_time_option(parser) # Cast 'time' argument to a Time object. parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time| self.time = time end end def specify_record_separator_option(parser) # Cast to octal integer. parser.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger, "Specify record separator (default \\0)") do |rs| self.record_separator = rs end end def list_example_option(parser) # List of arguments. parser.on("--list x,y,z", Array, "Example 'list' of arguments") do |list| self.list = list end end def specify_encoding_option(parser) # Keyword completion. We are specifying a specific set of arguments (CODES # and CODE_ALIASES - notice the latter is a Hash), and the user may provide # the shortest unambiguous text. code_list = (CODE_ALIASES.keys + CODES).join(', ') parser.on("--code CODE", CODES, CODE_ALIASES, "Select encoding", "(#{code_list})") do |encoding| self.encoding = encoding end end def optional_option_argument_with_keyword_completion_option(parser) # Optional '--type' option argument with keyword completion. parser.on("--type [TYPE]", [:text, :binary, :auto], "Select transfer type (text, binary, auto)") do |t| self.transfer_type = t end end def boolean_verbose_option(parser) # Boolean switch. parser.on("-v", "--[no-]verbose", "Run verbosely") do |v| self.verbose = v end end end # # Return a structure describing the options. # def parse(args) # The options specified on the command line will be collected in # *options*. @options = ScriptOptions.new @args = OptionParser.new do |parser| @options.define_options(parser) parser.parse!(args) end @options end attr_reader :parser, :options end # class OptparseExample example = OptparseExample.new options = example.parse(ARGV) pp options # example.options pp ARGV
Shell
Completion
For modern shells (e.g. bash, zsh, etc.), you can use shell completion for command line options.
The above examples should be enough to learn how to use this class. If you have any questions, file a ticket at bugs.ruby-lang.org.
The set of all prime numbers.
Prime.each(100) do |prime| p prime #=> 2, 3, 5, 7, 11, ...., 97 end
Prime
is Enumerable:
Prime.first 5 # => [2, 3, 5, 7, 11]
For convenience, each instance method of Prime
.instance can be accessed as a class method of Prime
.
e.g.
Prime.instance.prime?(2) #=> true Prime.prime?(2) #=> true
A “generator” provides an implementation of enumerating pseudo-prime numbers and it remembers the position of enumeration and upper bound. Furthermore, it is an external iterator of prime enumeration which is compatible with an Enumerator
.
Prime
::PseudoPrimeGenerator
is the base class for generators. There are few implementations of generator.
Prime
::EratosthenesGenerator
Uses eratosthenes’ sieve.
Prime
::TrialDivisionGenerator
Uses the trial division method.
Prime
::Generator23
Generates all positive integers which are not divisible by either 2 or 3. This sequence is very bad as a pseudo-prime sequence. But this is faster and uses much less memory than the other generators. So, it is suitable for factorizing an integer which is not large but has many prime factors. e.g. for Prime#prime?
.
This class watches for termination of multiple threads. Basic functionality (wait until specified threads have terminated) can be accessed through the class method ThreadsWait::all_waits
. Finer control can be gained using instance methods.
Example:
ThreadsWait.all_waits(thr1, thr2, ...) do |t| STDERR.puts "Thread #{t} has terminated." end th = ThreadsWait.new(thread1,...) th.next_wait # next one to be done
This class watches for termination of multiple threads. Basic functionality (wait until specified threads have terminated) can be accessed through the class method ThreadsWait::all_waits
. Finer control can be gained using instance methods.
Example:
ThreadsWait.all_waits(thr1, thr2, ...) do |t| STDERR.puts "Thread #{t} has terminated." end th = ThreadsWait.new(thread1,...) th.next_wait # next one to be done
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
This is a deprecated class, base class for C extensions using Data_Make_Struct or Data_Wrap_Struct.
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 "Whats 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 #=> "Whats 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 "Whats 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 }
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 { ... } 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 Any thread can raise an exception using the raise
instance method, which operates similarly to Kernel#raise
.
However, it’s important to note that an exception that occurs in any thread except the main thread depends on abort_on_exception
. This option is false
by default, meaning that any unhandled exception will cause the thread to terminate silently when waited on by either join
or value
. You can change this default by either abort_on_exception=
true
or setting $DEBUG to true
.
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.
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.
Raised when an invalid operation is attempted on a thread.
For example, when no other thread has been started:
Thread.stop
This will raises the following exception:
ThreadError: stopping only thread note: use sleep to stop forever
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"
The Comparable
mixin is used by classes whose objects may be ordered. The class must define the <=>
operator, which compares the receiver against another object, returning -1, 0, or +1 depending on whether the receiver is less than, equal to, or greater than the other object. If the other object is not comparable then the <=>
operator should return nil. Comparable
uses <=>
to implement the conventional comparison operators (<
, <=
, ==
, >=
, and >
) and the method between?
.
class SizeMatters include Comparable attr :str def <=>(other) str.size <=> other.str.size end def initialize(str) @str = str end def inspect @str end end s1 = SizeMatters.new("Z") s2 = SizeMatters.new("YY") s3 = SizeMatters.new("XXX") s4 = SizeMatters.new("WWWW") s5 = SizeMatters.new("VVVVV") s1 < s2 #=> true s4.between?(s1, s3) #=> false s4.between?(s3, s5) #=> true [ s3, s2, s5, s4, s1 ].sort #=> [Z, YY, XXX, WWWW, VVVVV]
The Enumerable
mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each
, which yields successive members of the collection. If Enumerable#max
, #min
, or #sort
is used, the objects in the collection must also implement a meaningful <=>
operator, as these methods rely on an ordering between members of the collection.
The objspace library extends the ObjectSpace
module and adds several methods to get internal statistic information about object/memory management.
You need to require 'objspace'
to use this extension module.
Generally, you *SHOULD NOT* use this library if you do not know about the MRI implementation. Mainly, this library is for (memory) profiler developers and MRI developers who need to know about MRI memory usage.
The ObjectSpace
module contains a number of routines that interact with the garbage collection facility and allow you to traverse all living objects with an iterator.
ObjectSpace
also provides support for object finalizers, procs that will be called when a specific object is about to be destroyed by garbage collection.
require 'objspace' a = "A" b = "B" ObjectSpace.define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" }) ObjectSpace.define_finalizer(b, proc {|id| puts "Finalizer two on #{id}" })
produces:
Finalizer two on 537763470 Finalizer one on 537763480
Helper module for easily defining exceptions with predefined messages.
1.
class Foo extend Exception2MessageMapper def_e2message ExistingExceptionClass, "message..." def_exception :NewExceptionClass, "message..."[, superclass] ... end
2.
module Error extend Exception2MessageMapper def_e2message ExistingExceptionClass, "message..." def_exception :NewExceptionClass, "message..."[, superclass] ... end class Foo include Error ... end foo = Foo.new foo.Fail ....
3.
module Error extend Exception2MessageMapper def_e2message ExistingExceptionClass, "message..." def_exception :NewExceptionClass, "message..."[, superclass] ... end class Foo extend Exception2MessageMapper include Error ... end Foo.Fail NewExceptionClass, arg... Foo.Fail ExistingExceptionClass, arg...
YAML Ain’t Markup Language
This module provides a Ruby interface for data serialization in YAML format.
The YAML module is an alias of Psych
, the YAML engine for Ruby.
Working with YAML can be very simple, for example:
require 'yaml' # Parse a YAML string YAML.load("--- foo") #=> "foo" # Emit some YAML YAML.dump("foo") # => "--- foo\n...\n" { :a => 'b'}.to_yaml # => "---\n:a: b\n"
As the implementation is provided by the Psych
library, detailed documentation can be found in that library’s docs (also part of standard library).
Do not use YAML to load untrusted data. Doing so is unsafe and could allow malicious input to execute arbitrary code inside your application. Please see doc/security.rdoc for more information.
Syck
was the original for YAML implementation in Ruby’s standard library developed by why the lucky stiff.
You can still use Syck
, if you prefer, for parsing and emitting YAML, but you must install the ‘syck’ gem now in order to use it.
In older Ruby versions, ie. <= 1.9, Syck
is still provided, however it was completely removed with the release of Ruby 2.0.0.
For more advanced details on the implementation see Psych
, and also check out yaml.org for spec details and other helpful information.
Psych
is maintained by Aaron Patterson on github: github.com/tenderlove/psych
Syck
can also be found on github: github.com/tenderlove/syck
Timeout
long-running blocks
require 'timeout' status = Timeout::timeout(5) { # Something that should be interrupted if it takes more than 5 seconds... }
Timeout
provides a way to auto-terminate a potentially long-running operation if it hasn’t finished in a fixed amount of time.
Previous versions didn’t use a module for namespacing, however timeout
is provided for backwards compatibility. You should prefer Timeout.timeout
instead.
© 2000 Network Applied Communication Laboratory, Inc.
© 2000 Information-technology Promotion Agency, Japan
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.
You don’t want to use this class. Really. Use XPath
, which is a wrapper for this class. Believe me. You don’t want to poke around in here. There is strange, dark magic at work in this code. Beware. Go back! Go back while you still can!
An X.509 name represents a hostname, email address or other entity associated with a public key.
You can create a Name
by parsing a distinguished name String
or by supplying the distinguished name as an Array
.
name = OpenSSL::X509::Name.parse 'CN=nobody/DC=example' name = OpenSSL::X509::Name.new [['CN', 'nobody'], ['DC', 'example']]
Authenticator for the “LOGIN” authentication type. See authenticate().
Authenticator for the “PLAIN” authentication type. See authenticate().