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
Raised when the arguments are wrong and there isn’t a more specific Exception
class.
Ex: passing the wrong number of arguments
[1, 2, 3].first(4, 5)
raises the exception:
ArgumentError: wrong number of arguments (given 2, expected 1)
Ex: passing an argument that is not acceptable:
[1, 2, 3].first(-4)
raises the exception:
ArgumentError: negative array size
Raised when a feature is not implemented on the current platform. For example, methods depending on the fsync
or fork
system calls may raise this exception if the underlying operating system or Ruby runtime does not support them.
Note that if fork
raises a NotImplementedError
, then respond_to?(:fork)
returns false
.
A generic error class raised when an invalid operation is attempted. Kernel#raise
will raise a RuntimeError
if no Exception
class is specified.
raise "ouch"
raises the exception:
RuntimeError: ouch
Raised when memory allocation fails.
Class Date provides methods for storing and manipulating calendar dates.
Consider using class Time instead of class Date if:
You need both dates and times; Date handles only dates.
You need only Gregorian dates (and not Julian dates); see Julian and Gregorian Calendars.
A Date object, once created, is immutable, and cannot be modified.
You can create a date for the current date, using Date.today
:
Date.today # => #<Date: 1999-12-31>
You can create a specific date from various combinations of arguments:
Date.new
takes integer year, month, and day-of-month:
Date.new(1999, 12, 31) # => #<Date: 1999-12-31>
Date.ordinal
takes integer year and day-of-year:
Date.ordinal(1999, 365) # => #<Date: 1999-12-31>
Date.jd
takes integer Julian day:
Date.jd(2451544) # => #<Date: 1999-12-31>
Date.commercial
takes integer commercial data (year, week, day-of-week):
Date.commercial(1999, 52, 5) # => #<Date: 1999-12-31>
Date.parse
takes a string, which it parses heuristically:
Date.parse('1999-12-31') # => #<Date: 1999-12-31> Date.parse('31-12-1999') # => #<Date: 1999-12-31> Date.parse('1999-365') # => #<Date: 1999-12-31> Date.parse('1999-W52-5') # => #<Date: 1999-12-31>
Date.strptime
takes a date string and a format string, then parses the date string according to the format string:
Date.strptime('1999-12-31', '%Y-%m-%d') # => #<Date: 1999-12-31> Date.strptime('31-12-1999', '%d-%m-%Y') # => #<Date: 1999-12-31> Date.strptime('1999-365', '%Y-%j') # => #<Date: 1999-12-31> Date.strptime('1999-W52-5', '%G-W%V-%u') # => #<Date: 1999-12-31> Date.strptime('1999 52 5', '%Y %U %w') # => #<Date: 1999-12-31> Date.strptime('1999 52 5', '%Y %W %u') # => #<Date: 1999-12-31> Date.strptime('fri31dec99', '%a%d%b%y') # => #<Date: 1999-12-31>
See also the specialized methods in “Specialized Format Strings” in Formats for Dates and Times
limit
Certain singleton methods in Date that parse string arguments also take optional keyword argument limit
, which can limit the length of the string argument.
When limit
is:
Non-negative: raises ArgumentError
if the string length is greater than limit.
Other numeric or nil
: ignores limit
.
Other non-numeric: raises TypeError
.
A Time
object represents a date and time:
Time.new(2000, 1, 1, 0, 0, 0) # => 2000-01-01 00:00:00 -0600
Although its value can be expressed as a single numeric (see Epoch Seconds below), it can be convenient to deal with the value by parts:
t = Time.new(-2000, 1, 1, 0, 0, 0.0) # => -2000-01-01 00:00:00 -0600 t.year # => -2000 t.month # => 1 t.mday # => 1 t.hour # => 0 t.min # => 0 t.sec # => 0 t.subsec # => 0 t = Time.new(2000, 12, 31, 23, 59, 59.5) # => 2000-12-31 23:59:59.5 -0600 t.year # => 2000 t.month # => 12 t.mday # => 31 t.hour # => 23 t.min # => 59 t.sec # => 59 t.subsec # => (1/2)
Epoch seconds is the exact number of seconds (including fractional subseconds) since the Unix Epoch, January 1, 1970.
You can retrieve that value exactly using method Time.to_r
:
Time.at(0).to_r # => (0/1) Time.at(0.999999).to_r # => (9007190247541737/9007199254740992)
Other retrieval methods such as Time#to_i
and Time#to_f
may return a value that rounds or truncates subseconds.
A Time
object derived from the system clock (for example, by method Time.now
) has the resolution supported by the system.
All of these examples were done using the EST timezone which is GMT-5.
Time
Instance You can create a new instance of Time
with Time.new
. This will use the current system time. Time.now
is an alias for this. You can also pass parts of the time to Time.new
such as year, month, minute, etc. When you want to construct a time this way you must pass at least a year. If you pass the year with nothing else time will default to January 1 of that year at 00:00:00 with the current system timezone. Here are some examples:
Time.new(2002) #=> 2002-01-01 00:00:00 -0500 Time.new(2002, 10) #=> 2002-10-01 00:00:00 -0500 Time.new(2002, 10, 31) #=> 2002-10-31 00:00:00 -0500
You can pass a UTC offset:
Time.new(2002, 10, 31, 2, 2, 2, "+02:00") #=> 2002-10-31 02:02:02 +0200
zone = timezone("Europe/Athens") # Eastern European Time, UTC+2 Time.new(2002, 10, 31, 2, 2, 2, zone) #=> 2002-10-31 02:02:02 +0200
You can also use Time.local
and Time.utc
to infer local and UTC timezones instead of using the current system setting.
You can also create a new time using Time.at
which takes the number of seconds (with subsecond) since the Unix Epoch.
Time.at(628232400) #=> 1989-11-28 00:00:00 -0500
Time
Once you have an instance of Time
there is a multitude of things you can do with it. Below are some examples. For all of the following examples, we will work on the assumption that you have done the following:
t = Time.new(1993, 02, 24, 12, 0, 0, "+09:00")
Was that a monday?
t.monday? #=> false
What year was that again?
t.year #=> 1993
Was it daylight savings at the time?
t.dst? #=> false
What’s the day a year later?
t + (60*60*24*365) #=> 1994-02-24 12:00:00 +0900
How many seconds was that since the Unix Epoch?
t.to_i #=> 730522800
You can also do standard functions like compare two times.
t1 = Time.new(2010) t2 = Time.new(2011) t1 == t2 #=> false t1 == t1 #=> true t1 < t2 #=> true t1 > t2 #=> false Time.new(2010,10,31).between?(t1, t2) #=> true
First, what’s elsewhere. Class Time
:
Inherits from class Object.
Includes module Comparable.
Here, class Time
provides methods that are useful for:
{Creating Time
objects}[rdoc-ref:Time@Methods+for+Creating].
{Fetching Time
values}[rdoc-ref:Time@Methods+for+Fetching].
{Querying a Time
object}[rdoc-ref:Time@Methods+for+Querying].
{Comparing Time
objects}[rdoc-ref:Time@Methods+for+Comparing].
{Converting a Time
object}[rdoc-ref:Time@Methods+for+Converting].
{Rounding a Time
}.
::new
: Returns a new time from specified arguments (year, month, etc.), including an optional timezone value.
::local
(aliased as ::mktime
): Same as ::new
, except the timezone is the local timezone.
::utc
(aliased as ::gm
): Same as ::new
, except the timezone is UTC.
::at
: Returns a new time based on seconds since epoch.
::now
: Returns a new time based on the current system time.
+
(plus): Returns a new time increased by the given number of seconds.
-
(minus): Returns a new time decreased by the given number of seconds.
year
: Returns the year of the time.
hour
: Returns the hours value for the time.
min
: Returns the minutes value for the time.
sec
: Returns the seconds value for the time.
usec
(aliased as tv_usec
): Returns the number of microseconds in the subseconds value of the time.
nsec
(aliased as tv_nsec
: Returns the number of nanoseconds in the subsecond part of the time.
subsec
: Returns the subseconds value for the time.
wday
: Returns the integer weekday value of the time (0 == Sunday).
yday
: Returns the integer yearday value of the time (1 == January 1).
hash
: Returns the integer hash value for the time.
utc_offset
(aliased as gmt_offset
and gmtoff
): Returns the offset in seconds between time and UTC.
to_f
: Returns the float number of seconds since epoch for the time.
to_i
(aliased as tv_sec
): Returns the integer number of seconds since epoch for the time.
to_r
: Returns the Rational
number of seconds since epoch for the time.
zone
: Returns a string representation of the timezone of the time.
dst?
(aliased as isdst
): Returns whether the time is DST (daylight saving time).
sunday?
: Returns whether the time is a Sunday.
monday?
: Returns whether the time is a Monday.
tuesday?
: Returns whether the time is a Tuesday.
wednesday?
: Returns whether the time is a Wednesday.
thursday?
: Returns whether the time is a Thursday.
friday?
: Returns whether time is a Friday.
saturday?
: Returns whether the time is a Saturday.
inspect
: Returns the time in detail as a string.
strftime
: Returns the time as a string, according to a given format.
to_a
: Returns a 10-element array of values from the time.
to_s
: Returns a string representation of the time.
getutc
(aliased as getgm
): Returns a new time converted to UTC.
getlocal
: Returns a new time converted to local time.
localtime
: Converts time to local time in place.
deconstruct_keys
: Returns a hash of time components used in pattern-matching.
round
:Returns a new time with subseconds rounded.
ceil
: Returns a new time with subseconds raised to a ceiling.
floor
: Returns a new time with subseconds lowered to a floor.
For the forms of argument zone
, see Timezone Specifiers.
Certain Time
methods accept arguments that specify timezones:
Time.at
: keyword argument in:
.
Time.new
: positional argument zone
or keyword argument in:
.
Time.now
: keyword argument in:
.
Time#getlocal
: positional argument zone
.
Time#localtime
: positional argument zone
.
The value given with any of these must be one of the following (each detailed below):
The zone value may be a string offset from UTC in the form '+HH:MM'
or '-HH:MM'
, where:
HH
is the 2-digit hour in the range 0..23
.
MM
is the 2-digit minute in the range 0..59
.
Examples:
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC Time.at(t, in: '-23:59') # => 1999-12-31 20:16:01 -2359 Time.at(t, in: '+23:59') # => 2000-01-02 20:14:01 +2359
The zone value may be a letter in the range 'A'..'I'
or 'K'..'Z'
; see List of military time zones:
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC Time.at(t, in: 'A') # => 2000-01-01 21:15:01 +0100 Time.at(t, in: 'I') # => 2000-01-02 05:15:01 +0900 Time.at(t, in: 'K') # => 2000-01-02 06:15:01 +1000 Time.at(t, in: 'Y') # => 2000-01-01 08:15:01 -1200 Time.at(t, in: 'Z') # => 2000-01-01 20:15:01 UTC
The zone value may be an integer number of seconds in the range -86399..86399
:
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC Time.at(t, in: -86399) # => 1999-12-31 20:15:02 -235959 Time.at(t, in: 86399) # => 2000-01-02 20:15:00 +235959
The zone value may be an object responding to certain timezone methods, an instance of Timezone and TZInfo for example.
The timezone methods are:
local_to_utc
:
Called when Time.new
is invoked with tz
as the value of positional argument zone
or keyword argument in:
.
Argument: a Time-like object.
Returns: a Time-like object in the UTC timezone.
utc_to_local
:
Called when Time.at
or Time.now
is invoked with tz
as the value for keyword argument in:
, and when Time#getlocal
or Time#localtime
is called with tz
as the value for positional argument zone
.
Argument: a Time-like object.
Returns: a Time-like object in the local timezone.
A custom timezone class may have these instance methods, which will be called if defined:
abbr
:
Called when Time#strftime
is invoked with a format involving %Z
.
Argument: a Time-like object.
Returns: a string abbreviation for the timezone name.
dst?
:
Called when Time.at
or Time.now
is invoked with tz
as the value for keyword argument in:
, and when Time#getlocal
or Time#localtime
is called with tz
as the value for positional argument zone
.
Argument: a Time-like object.
Returns: whether the time is daylight saving time.
name
:
Called when Marshal.dump(t)
is invoked
Argument: none.
Returns: the string name of the timezone.
Time
-Like Objects A Time
-like object is a container object capable of interfacing with timezone libraries for timezone conversion.
The argument to the timezone conversion methods above will have attributes similar to Time
, except that timezone related attributes are meaningless.
The objects returned by local_to_utc
and utc_to_local
methods of the timezone object may be of the same class as their arguments, of arbitrary object classes, or of class Integer
.
For a returned class other than Integer
, the class must have the following methods:
year
mon
mday
hour
min
sec
isdst
to_i
For a returned Integer
, its components, decomposed in UTC, are interpreted as times in the specified timezone.
If the class (the receiver of class methods, or the class of the receiver of instance methods) has find_timezone
singleton method, this method is called to achieve the corresponding timezone object from a timezone name.
For example, using Timezone:
class TimeWithTimezone < Time require 'timezone' def self.find_timezone(z) = Timezone[z] end TimeWithTimezone.now(in: "America/New_York") #=> 2023-12-25 00:00:00 -0500 TimeWithTimezone.new("2023-12-25 America/New_York") #=> 2023-12-25 00:00:00 -0500
Or, using TZInfo:
class TimeWithTZInfo < Time require 'tzinfo' def self.find_timezone(z) = TZInfo::Timezone.get(z) end TimeWithTZInfo.now(in: "America/New_York") #=> 2023-12-25 00:00:00 -0500 TimeWithTZInfo.new("2023-12-25 America/New_York") #=> 2023-12-25 00:00:00 -0500
You can define this method per subclasses, or on the toplevel Time
class.
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
This library provides three different ways to delegate method calls to an object. The easiest to use is SimpleDelegator
. Pass an object to the constructor and all methods supported by the object will be delegated. This object can be changed later.
Going a step further, the top level DelegateClass method allows you to easily setup delegation through class inheritance. This is considerably more flexible and thus probably the most common use for this library.
Finally, if you need full control over the delegation scheme, you can inherit from the abstract class Delegator
and customize as needed. (If you find yourself needing this control, have a look at Forwardable
which is also in the standard library. It may suit your needs better.)
SimpleDelegator’s implementation serves as a nice example of the use of Delegator:
require 'delegate' class SimpleDelegator < Delegator def __getobj__ @delegate_sd_obj # return object we are delegating to, required end def __setobj__(obj) @delegate_sd_obj = obj # change delegation object, # a feature we're providing end end
Be advised, RDoc
will not detect delegated methods.
A concrete implementation of Delegator
, this class provides the means to delegate all supported method calls to the object passed into the constructor and even to change the object being delegated to at a later time with __setobj__
.
class User def born_on Date.new(1989, 9, 10) end end require 'delegate' class UserDecorator < SimpleDelegator def birth_year born_on.year end end decorated_user = UserDecorator.new(User.new) decorated_user.birth_year #=> 1989 decorated_user.__getobj__ #=> #<User: ...>
A SimpleDelegator
instance can take advantage of the fact that SimpleDelegator
is a subclass of Delegator
to call super
to have methods called on the object being delegated to.
class SuperArray < SimpleDelegator def [](*args) super + 1 end end SuperArray.new([1])[0] #=> 2
Here’s a simple example that takes advantage of the fact that SimpleDelegator’s delegation object can be changed at any time.
class Stats def initialize @source = SimpleDelegator.new([]) end def stats(records) @source.__setobj__(records) "Elements: #{@source.size}\n" + " Non-Nil: #{@source.compact.size}\n" + " Unique: #{@source.uniq.size}\n" end end s = Stats.new puts s.stats(%w{James Edward Gray II}) puts puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
Prints:
Elements: 4 Non-Nil: 4 Unique: 4 Elements: 8 Non-Nil: 7 Unique: 6
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>
OptionParser
OptionParser
? See the Tutorial.
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 |parser| parser.banner = "Usage: example.rb [options]" parser.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 |parser| parser.banner = "Usage: example.rb [options]" parser.on("-nNAME", "--name=NAME", "Name to say hello to") do |n| args.name = n end parser.on("-h", "--help", "Prints this help") do puts parser 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
(need to require optparse/date
)
DateTime
– Anything accepted by DateTime.parse
(need to require optparse/date
)
Time
– Anything accepted by Time.httpdate
or Time.parse
(need to require optparse/time
)
URI
– Anything accepted by URI.parse
(need to require optparse/uri
)
Shellwords
– Anything accepted by Shellwords.shellwords
(need to require optparse/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 below.
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' options = {} OptionParser.new do |parser| parser.on('-a') parser.on('-b NUM', Integer) parser.on('-v', '--verbose') end.parse!(into: options) p options
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
Completion
For modern shells (e.g. bash, zsh, etc.), you can use shell completion for command line options.
The above examples, along with the accompanying Tutorial, should be enough to learn how to use this class. If you have any questions, file a ticket at bugs.ruby-lang.org.
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.
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
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
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.
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 a value less than 0, returning 0, or returning a value greater than 0, 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 StringSorter include Comparable attr :str def <=>(other) str.size <=> other.str.size end def initialize(str) @str = str end def inspect @str end end s1 = StringSorter.new("Z") s2 = StringSorter.new("YY") s3 = StringSorter.new("XXX") s4 = StringSorter.new("WWWW") s5 = StringSorter.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]
Module Comparable provides these methods, all of which use method <=>
:
<
: Returns whether self
is less than the given object.
<=
: Returns whether self
is less than or equal to the given object.
==
: Returns whether self
is equal to the given object.
>
: Returns whether self
is greater than the given object.
>=
: Returns whether self
is greater than or equal to the given object.
between?
: Returns true
if self
is between two given objects.
clamp
: For given objects min
and max
, or range (min..max)
, returns:
min
if (self <=> min) < 0
.
max
if (self <=> max) > 0
.
self
otherwise.
Module Enumerable provides methods that are useful to a collection class for:
These methods return information about the Enumerable other than the elements themselves:
include?
, member?
: Returns true
if self == object
, false
otherwise.
all?
: Returns true
if all elements meet a specified criterion; false
otherwise.
any?
: Returns true
if any element meets a specified criterion; false
otherwise.
none?
: Returns true
if no element meets a specified criterion; false
otherwise.
one?
: Returns true
if exactly one element meets a specified criterion; false
otherwise.
count
: Returns the count of elements, based on an argument or block criterion, if given.
tally
: Returns a new Hash
containing the counts of occurrences of each element.
These methods return entries from the Enumerable, without modifying it:
Leading, trailing, or all elements:
first
: Returns the first element or leading elements.
take
: Returns a specified number of leading elements.
drop
: Returns a specified number of trailing elements.
take_while
: Returns leading elements as specified by the given block.
drop_while
: Returns trailing elements as specified by the given block.
Minimum and maximum value elements:
min
: Returns the elements whose values are smallest among the elements, as determined by <=>
or a given block.
max
: Returns the elements whose values are largest among the elements, as determined by <=>
or a given block.
minmax
: Returns a 2-element Array
containing the smallest and largest elements.
min_by
: Returns the smallest element, as determined by the given block.
max_by
: Returns the largest element, as determined by the given block.
minmax_by
: Returns the smallest and largest elements, as determined by the given block.
Groups, slices, and partitions:
group_by
: Returns a Hash
that partitions the elements into groups.
partition
: Returns elements partitioned into two new Arrays, as determined by the given block.
slice_after
: Returns a new Enumerator
whose entries are a partition of self
, based either on a given object
or a given block.
slice_before
: Returns a new Enumerator
whose entries are a partition of self
, based either on a given object
or a given block.
slice_when
: Returns a new Enumerator
whose entries are a partition of self
based on the given block.
chunk
: Returns elements organized into chunks as specified by the given block.
chunk_while
: Returns elements organized into chunks as specified by the given block.
These methods return elements that meet a specified criterion:
find_all
, filter
, select
: Returns elements selected by the block.
find_index
: Returns the index of an element selected by a given object or block.
reject
: Returns elements not rejected by the block.
uniq
: Returns elements that are not duplicates.
These methods return elements in sorted order:
sort
: Returns the elements, sorted by <=>
or the given block.
sort_by
: Returns the elements, sorted by the given block.
each_entry
: Calls the block with each successive element (slightly different from each).
each_with_index
: Calls the block with each successive element and its index.
each_with_object
: Calls the block with each successive element and a given object.
each_slice
: Calls the block with successive non-overlapping slices.
each_cons
: Calls the block with successive overlapping slices. (different from each_slice
).
reverse_each
: Calls the block with each successive element, in reverse order.
filter_map
: Returns truthy objects returned by the block.
flat_map
, collect_concat
: Returns flattened objects returned by the block.
grep
: Returns elements selected by a given object or objects returned by a given block.
grep_v
: Returns elements selected by a given object or objects returned by a given block.
reduce
, inject
: Returns the object formed by combining all elements.
sum
: Returns the sum of the elements, using method +
.
zip
: Combines each element with elements from other enumerables; returns the n-tuples or calls the block with each.
cycle
: Calls the block with each element, cycling repeatedly.
To use module Enumerable in a collection class:
Include it:
include Enumerable
Implement method #each
which must yield successive elements of the collection. The method will be called by almost any Enumerable method.
Example:
class Foo include Enumerable def each yield 1 yield 1, 2 yield end end Foo.new.each_entry{ |element| p element }
Output:
1 [1, 2] nil
These Ruby core classes include (or extend) Enumerable:
These Ruby standard library classes include Enumerable:
Virtually all methods in Enumerable call method #each
in the including class:
Hash#each
yields the next key-value pair as a 2-element Array
.
Struct#each
yields the next name-value pair as a 2-element Array
.
For the other classes above, #each
yields the next object from the collection.
The example code snippets for the Enumerable methods:
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. See the documentation for ObjectSpace.define_finalizer
for important information on how to use this method correctly.
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}" }) a = nil b = nil
produces:
Finalizer two on 537763470 Finalizer one on 537763480
The DidYouMean
gem adds functionality to suggest possible method/class names upon errors such as NameError
and NoMethodError
. In Ruby 2.3 or later, it is automatically activated during startup.
@example
methosd # => NameError: undefined local variable or method `methosd' for main:Object # Did you mean? methods # method OBject # => NameError: uninitialized constant OBject # Did you mean? Object @full_name = "Yuki Nishijima" first_name, last_name = full_name.split(" ") # => NameError: undefined local variable or method `full_name' for main:Object # Did you mean? @full_name @@full_name = "Yuki Nishijima" @@full_anme # => NameError: uninitialized class variable @@full_anme in Object # Did you mean? @@full_name full_name = "Yuki Nishijima" full_name.starts_with?("Y") # => NoMethodError: undefined method `starts_with?' for "Yuki Nishijima":String # Did you mean? start_with? hash = {foo: 1, bar: 2, baz: 3} hash.fetch(:fooo) # => KeyError: key not found: :fooo # Did you mean? :foo
did_you_mean
Occasionally, you may want to disable the did_you_mean
gem for e.g. debugging issues in the error object itself. You can disable it entirely by specifying --disable-did_you_mean
option to the ruby
command:
$ ruby --disable-did_you_mean -e "1.zeor?" -e:1:in `<main>': undefined method `zeor?' for 1:Integer (NameError)
When you do not have direct access to the ruby
command (e.g. +rails console+, irb
), you could applyoptions using the RUBYOPT
environment variable:
$ RUBYOPT='--disable-did_you_mean' irb irb:0> 1.zeor? # => NoMethodError (undefined method `zeor?' for 1:Integer)
Sometimes, you do not want to disable the gem entirely, but need to get the original error message without suggestions (e.g. testing). In this case, you could use the #original_message
method on the error object:
no_method_error = begin 1.zeor? rescue NoMethodError => error error end no_method_error.message # => NoMethodError (undefined method `zeor?' for 1:Integer) # Did you mean? zero? no_method_error.original_message # => NoMethodError (undefined method `zeor?' for 1:Integer)
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
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 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/ruby/psych
Syck can also be found on github: github.com/ruby/syck