Mixin methods for install and update options for Gem::Commands
Helper methods for both Gem::Installer
and Gem::Uninstaller
Raised when an invalid operation is attempted on a Fiber
, in particular when attempting to call/resume a dead fiber, attempting to yield from the root fiber, or calling a fiber across threads.
fiber = Fiber.new{} fiber.resume #=> nil fiber.resume #=> FiberError: dead fiber called
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 Module
is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not. Conversely, module methods may be called without creating an encapsulating object, while instance methods may not. (See Module#module_function
.)
In the descriptions that follow, the parameter sym refers to a symbol, which is either a quoted string or a Symbol
(such as :name
).
module Mod include Math CONST = 1 def meth # ... end end Mod.class #=> Module Mod.constants #=> [:CONST, :PI, :E] Mod.instance_methods #=> [:meth]
A regular expression (also called a regexp) is a match pattern (also simply called a pattern).
A common notation for a regexp uses enclosing slash characters:
/foo/
A regexp may be applied to a target string; The part of the string (if any) that matches the pattern is called a match, and may be said to match:
re = /red/ re.match?('redirect') # => true # Match at beginning of target. re.match?('bored') # => true # Match at end of target. re.match?('credit') # => true # Match within target. re.match?('foo') # => false # No match.
A regexp may be used:
To extract substrings based on a given pattern:
re = /foo/ # => /foo/ re.match('food') # => #<MatchData "foo"> re.match('good') # => nil
See sections Method match and Operator =~.
To determine whether a string matches a given pattern:
re.match?('food') # => true re.match?('good') # => false
See section Method match?.
As an argument for calls to certain methods in other classes and modules; most such methods accept an argument that may be either a string or the (much more powerful) regexp.
See Regexp Methods.
A regexp object has:
A source; see Sources.
Several modes; see Modes.
A timeout; see Timeouts.
An encoding; see Encodings.
A regular expression may be created with:
A regexp literal using slash characters (see Regexp Literals):
# This is a very common usage. /foo/ # => /foo/
A %r
regexp literal (see Regexp Literals):
# Same delimiter character at beginning and end; # useful for avoiding escaping characters %r/name\/value pair/ # => /name\/value pair/ %r:name/value pair: # => /name\/value pair/ %r|name/value pair| # => /name\/value pair/ # Certain "paired" characters can be delimiters. %r[foo] # => /foo/ %r{foo} # => /foo/ %r(foo) # => /foo/ %r<foo> # => /foo/
Method Regexp.new
.
match
Each of the methods Regexp#match
, String#match
, and Symbol#match
returns a MatchData
object if a match was found, nil
otherwise; each also sets global variables:
'food'.match(/foo/) # => #<MatchData "foo"> 'food'.match(/bar/) # => nil
=~
Each of the operators Regexp#=~
, String#=~
, and Symbol#=~
returns an integer offset if a match was found, nil
otherwise; each also sets global variables:
/bar/ =~ 'foo bar' # => 4 'foo bar' =~ /bar/ # => 4 /baz/ =~ 'foo bar' # => nil
match?
Each of the methods Regexp#match?
, String#match?
, and Symbol#match?
returns true
if a match was found, false
otherwise; none sets global variables:
'food'.match?(/foo/) # => true 'food'.match?(/bar/) # => false
Certain regexp-oriented methods assign values to global variables:
match
: see Method match.
=~
: see Operator =~.
The affected global variables are:
$~
: Returns a MatchData
object, or nil
.
$&
: Returns the matched part of the string, or nil
.
$`
: Returns the part of the string to the left of the match, or nil
.
$'
: Returns the part of the string to the right of the match, or nil
.
$+
: Returns the last group matched, or nil
.
$1
, $2
, etc.: Returns the first, second, etc., matched group, or nil
. Note that $0
is quite different; it returns the name of the currently executing program.
Examples:
# Matched string, but no matched groups. 'foo bar bar baz'.match('bar') $~ # => #<MatchData "bar"> $& # => "bar" $` # => "foo " $' # => " bar baz" $+ # => nil $1 # => nil # Matched groups. /s(\w{2}).*(c)/.match('haystack') $~ # => #<MatchData "stac" 1:"ta" 2:"c"> $& # => "stac" $` # => "hay" $' # => "k" $+ # => "c" $1 # => "ta" $2 # => "c" $3 # => nil # No match. 'foo'.match('bar') $~ # => nil $& # => nil $` # => nil $' # => nil $+ # => nil $1 # => nil
Note that Regexp#match?
, String#match?
, and Symbol#match?
do not set global variables.
As seen above, the simplest regexp uses a literal expression as its source:
re = /foo/ # => /foo/ re.match('food') # => #<MatchData "foo"> re.match('good') # => nil
A rich collection of available subexpressions gives the regexp great power and flexibility:
Regexp special characters, called metacharacters, have special meanings in certain contexts; depending on the context, these are sometimes metacharacters:
. ? - + * ^ \ | $ ( ) [ ] { }
To match a metacharacter literally, backslash-escape it:
# Matches one or more 'o' characters. /o+/.match('foo') # => #<MatchData "oo"> # Would match 'o+'. /o\+/.match('foo') # => nil
To match a backslash literally, backslash-escape it:
/\./.match('\.') # => #<MatchData "."> /\\./.match('\.') # => #<MatchData "\\.">
Method
Regexp.escape
returns an escaped string:
Regexp.escape('.?-+*^\|$()[]{}') # => "\\.\\?\\-\\+\\*\\^\\\\\\|\\$\\(\\)\\[\\]\\{\\}"
The source literal largely behaves like a double-quoted string; see Regexp Literals.
In particular, a source literal may contain interpolated expressions:
s = 'foo' # => "foo" /#{s}/ # => /foo/ /#{s.capitalize}/ # => /Foo/ /#{2 + 2}/ # => /4/
There are differences between an ordinary string literal and a source literal; see Shorthand Character Classes.
\s
in an ordinary string literal is equivalent to a space character; in a source literal, it’s shorthand for matching a whitespace character.
In an ordinary string literal, these are (needlessly) escaped characters; in a source literal, they are shorthands for various matching characters:
\w \W \d \D \h \H \S \R
A character class is delimited by square brackets; it specifies that certain characters match at a given point in the target string:
# This character class will match any vowel. re = /B[aeiou]rd/ re.match('Bird') # => #<MatchData "Bird"> re.match('Bard') # => #<MatchData "Bard"> re.match('Byrd') # => nil
A character class may contain hyphen characters to specify ranges of characters:
# These regexps have the same effect. /[abcdef]/.match('foo') # => #<MatchData "f"> /[a-f]/.match('foo') # => #<MatchData "f"> /[a-cd-f]/.match('foo') # => #<MatchData "f">
When the first character of a character class is a caret (^
), the sense of the class is inverted: it matches any character except those specified.
/[^a-eg-z]/.match('f') # => #<MatchData "f">
A character class may contain another character class. By itself this isn’t useful because [a-z[0-9]]
describes the same set as [a-z0-9]
.
However, character classes also support the &&
operator, which performs set intersection on its arguments. The two can be combined as follows:
/[a-w&&[^c-g]z]/ # ([a-w] AND ([^c-g] OR z))
This is equivalent to:
/[abh-w]/
Each of the following metacharacters serves as a shorthand for a character class:
/./
: Matches any character except a newline:
/./.match('foo') # => #<MatchData "f"> /./.match("\n") # => nil
/./m
: Matches any character, including a newline; see Multiline Mode:
/./m.match("\n") # => #<MatchData "\n">
/\w/
: Matches a word character: equivalent to [a-zA-Z0-9_]
:
/\w/.match(' foo') # => #<MatchData "f"> /\w/.match(' _') # => #<MatchData "_"> /\w/.match(' ') # => nil
/\W/
: Matches a non-word character: equivalent to [^a-zA-Z0-9_]
:
/\W/.match(' ') # => #<MatchData " "> /\W/.match('_') # => nil
/\d/
: Matches a digit character: equivalent to [0-9]
:
/\d/.match('THX1138') # => #<MatchData "1"> /\d/.match('foo') # => nil
/\D/
: Matches a non-digit character: equivalent to [^0-9]
:
/\D/.match('123Jump!') # => #<MatchData "J"> /\D/.match('123') # => nil
/\h/
: Matches a hexdigit character: equivalent to [0-9a-fA-F]
:
/\h/.match('xyz fedcba9876543210') # => #<MatchData "f"> /\h/.match('xyz') # => nil
/\H/
: Matches a non-hexdigit character: equivalent to [^0-9a-fA-F]
:
/\H/.match('fedcba9876543210xyz') # => #<MatchData "x"> /\H/.match('fedcba9876543210') # => nil
/\s/
: Matches a whitespace character: equivalent to /[ \t\r\n\f\v]/
:
/\s/.match('foo bar') # => #<MatchData " "> /\s/.match('foo') # => nil
/\S/
: Matches a non-whitespace character: equivalent to /[^ \t\r\n\f\v]/
:
/\S/.match(" \t\r\n\f\v foo") # => #<MatchData "f"> /\S/.match(" \t\r\n\f\v") # => nil
/\R/
: Matches a linebreak, platform-independently:
/\R/.match("\r") # => #<MatchData "\r"> # Carriage return (CR) /\R/.match("\n") # => #<MatchData "\n"> # Newline (LF) /\R/.match("\f") # => #<MatchData "\f"> # Formfeed (FF) /\R/.match("\v") # => #<MatchData "\v"> # Vertical tab (VT) /\R/.match("\r\n") # => #<MatchData "\r\n"> # CRLF /\R/.match("\u0085") # => #<MatchData "\u0085"> # Next line (NEL) /\R/.match("\u2028") # => #<MatchData "\u2028"> # Line separator (LSEP) /\R/.match("\u2029") # => #<MatchData "\u2029"> # Paragraph separator (PSEP)
An anchor is a metasequence that matches a zero-width position between characters in the target string.
For a subexpression with no anchor, matching may begin anywhere in the target string:
/real/.match('surrealist') # => #<MatchData "real">
For a subexpression with an anchor, matching must begin at the matched anchor.
Each of these anchors matches a boundary:
^
: Matches the beginning of a line:
/^bar/.match("foo\nbar") # => #<MatchData "bar"> /^ar/.match("foo\nbar") # => nil
$
: Matches the end of a line:
/bar$/.match("foo\nbar") # => #<MatchData "bar"> /ba$/.match("foo\nbar") # => nil
\A
: Matches the beginning of the string:
/\Afoo/.match('foo bar') # => #<MatchData "foo"> /\Afoo/.match(' foo bar') # => nil
\Z
: Matches the end of the string; if string ends with a single newline, it matches just before the ending newline:
/foo\Z/.match('bar foo') # => #<MatchData "foo"> /foo\Z/.match('foo bar') # => nil /foo\Z/.match("bar foo\n") # => #<MatchData "foo"> /foo\Z/.match("bar foo\n\n") # => nil
\z
: Matches the end of the string:
/foo\z/.match('bar foo') # => #<MatchData "foo"> /foo\z/.match('foo bar') # => nil /foo\z/.match("bar foo\n") # => nil
\b
: Matches word boundary when not inside brackets; matches backspace ("0x08"
) when inside brackets:
/foo\b/.match('foo bar') # => #<MatchData "foo"> /foo\b/.match('foobar') # => nil
\B
: Matches non-word boundary:
/foo\B/.match('foobar') # => #<MatchData "foo"> /foo\B/.match('foo bar') # => nil
\G
: Matches first matching position:
In methods like String#gsub
and String#scan
, it changes on each iteration. It initially matches the beginning of subject, and in each following iteration it matches where the last match finished.
" a b c".gsub(/ /, '_') # => "____a_b_c" " a b c".gsub(/\G /, '_') # => "____a b c"
In methods like Regexp#match
and String#match
that take an optional offset, it matches where the search begins.
"hello, world".match(/,/, 3) # => #<MatchData ","> "hello, world".match(/\G,/, 3) # => nil
Lookahead anchors:
(?=pat)
: Positive lookahead assertion: ensures that the following characters match pat, but doesn’t include those characters in the matched substring.
(?!pat)
: Negative lookahead assertion: ensures that the following characters do not match pat, but doesn’t include those characters in the matched substring.
Lookbehind anchors:
(?<=pat)
: Positive lookbehind assertion: ensures that the preceding characters match pat, but doesn’t include those characters in the matched substring.
(?<!pat)
: Negative lookbehind assertion: ensures that the preceding characters do not match pat, but doesn’t include those characters in the matched substring.
The pattern below uses positive lookahead and positive lookbehind to match text appearing in … tags without including the tags in the match:
/(?<=<b>)\w+(?=<\/b>)/.match("Fortune favors the <b>bold</b>.") # => #<MatchData "bold">
\K
: Match reset: the matched content preceding \K
in the regexp is excluded from the result. For example, the following two regexps are almost equivalent:
/ab\Kc/.match('abc') # => #<MatchData "c"> /(?<=ab)c/.match('abc') # => #<MatchData "c">
These match same string and $&
equals 'c'
, while the matched position is different.
As are the following two regexps:
/(a)\K(b)\Kc/ /(?<=(?<=(a))(b))c/
The vertical bar metacharacter (|
) may be used within parentheses to express alternation: two or more subexpressions any of which may match the target string.
Two alternatives:
re = /(a|b)/ re.match('foo') # => nil re.match('bar') # => #<MatchData "b" 1:"b">
Four alternatives:
re = /(a|b|c|d)/ re.match('shazam') # => #<MatchData "a" 1:"a"> re.match('cold') # => #<MatchData "c" 1:"c">
Each alternative is a subexpression, and may be composed of other subexpressions:
re = /([a-c]|[x-z])/ re.match('bar') # => #<MatchData "b" 1:"b"> re.match('ooz') # => #<MatchData "z" 1:"z">
Method Regexp.union
provides a convenient way to construct a regexp with alternatives.
A simple regexp matches one character:
/\w/.match('Hello') # => #<MatchData "H">
An added quantifier specifies how many matches are required or allowed:
*
- Matches zero or more times:
/\w*/.match('') # => #<MatchData ""> /\w*/.match('x') # => #<MatchData "x"> /\w*/.match('xyz') # => #<MatchData "yz">
+
- Matches one or more times:
/\w+/.match('') # => nil /\w+/.match('x') # => #<MatchData "x"> /\w+/.match('xyz') # => #<MatchData "xyz">
?
- Matches zero or one times:
/\w?/.match('') # => #<MatchData ""> /\w?/.match('x') # => #<MatchData "x"> /\w?/.match('xyz') # => #<MatchData "x">
{
n}
- Matches exactly n times:
/\w{2}/.match('') # => nil /\w{2}/.match('x') # => nil /\w{2}/.match('xyz') # => #<MatchData "xy">
{
min,}
- Matches min or more times:
/\w{2,}/.match('') # => nil /\w{2,}/.match('x') # => nil /\w{2,}/.match('xy') # => #<MatchData "xy"> /\w{2,}/.match('xyz') # => #<MatchData "xyz">
{,
max}
- Matches max or fewer times:
/\w{,2}/.match('') # => #<MatchData ""> /\w{,2}/.match('x') # => #<MatchData "x"> /\w{,2}/.match('xyz') # => #<MatchData "xy">
{
min,
max}
- Matches at least min times and at most max times:
/\w{1,2}/.match('') # => nil /\w{1,2}/.match('x') # => #<MatchData "x"> /\w{1,2}/.match('xyz') # => #<MatchData "xy">
Quantifier matching may be greedy, lazy, or possessive:
In greedy matching, as many occurrences as possible are matched while still allowing the overall match to succeed. Greedy quantifiers: *
, +
, ?
, {min, max}
and its variants.
In lazy matching, the minimum number of occurrences are matched. Lazy quantifiers: *?
, +?
, ??
, {min, max}?
and its variants.
In possessive matching, once a match is found, there is no backtracking; that match is retained, even if it jeopardises the overall match. Possessive quantifiers: *+
, ++
, ?+
. Note that {min, max}
and its variants do not support possessive matching.
More:
About greedy and lazy matching, see Choosing Minimal or Maximal Repetition.
About possessive matching, see Eliminate Needless Backtracking.
A simple regexp has (at most) one match:
re = /\d\d\d\d-\d\d-\d\d/ re.match('1943-02-04') # => #<MatchData "1943-02-04"> re.match('1943-02-04').size # => 1 re.match('foo') # => nil
Adding one or more pairs of parentheses, (subexpression)
, defines groups, which may result in multiple matched substrings, called captures:
re = /(\d\d\d\d)-(\d\d)-(\d\d)/ re.match('1943-02-04') # => #<MatchData "1943-02-04" 1:"1943" 2:"02" 3:"04"> re.match('1943-02-04').size # => 4
The first capture is the entire matched string; the other captures are the matched substrings from the groups.
A group may have a quantifier:
re = /July 4(th)?/ re.match('July 4') # => #<MatchData "July 4" 1:nil> re.match('July 4th') # => #<MatchData "July 4th" 1:"th"> re = /(foo)*/ re.match('') # => #<MatchData "" 1:nil> re.match('foo') # => #<MatchData "foo" 1:"foo"> re.match('foofoo') # => #<MatchData "foofoo" 1:"foo"> re = /(foo)+/ re.match('') # => nil re.match('foo') # => #<MatchData "foo" 1:"foo"> re.match('foofoo') # => #<MatchData "foofoo" 1:"foo">
The returned MatchData object gives access to the matched substrings:
re = /(\d\d\d\d)-(\d\d)-(\d\d)/ md = re.match('1943-02-04') # => #<MatchData "1943-02-04" 1:"1943" 2:"02" 3:"04"> md[0] # => "1943-02-04" md[1] # => "1943" md[2] # => "02" md[3] # => "04"
A group may be made non-capturing; it is still a group (and, for example, can have a quantifier), but its matching substring is not included among the captures.
A non-capturing group begins with ?:
(inside the parentheses):
# Don't capture the year. re = /(?:\d\d\d\d)-(\d\d)-(\d\d)/ md = re.match('1943-02-04') # => #<MatchData "1943-02-04" 1:"02" 2:"04">
A group match may also be referenced within the regexp itself; such a reference is called a backreference
:
/[csh](..) [csh]\1 in/.match('The cat sat in the hat') # => #<MatchData "cat sat in" 1:"at">
This table shows how each subexpression in the regexp above matches a substring in the target string:
| Subexpression in Regexp | Matching Substring in Target String | |---------------------------|-------------------------------------| | First '[csh]' | Character 'c' | | '(..)' | First substring 'at' | | First space ' ' | First space character ' ' | | Second '[csh]' | Character 's' | | '\1' (backreference 'at') | Second substring 'at' | | ' in' | Substring ' in' |
A regexp may contain any number of groups:
For a large number of groups:
The ordinary \n
notation applies only for n in range (1..9).
The MatchData[n]
notation applies for any non-negative n.
\0
is a special backreference, referring to the entire matched string; it may not be used within the regexp itself, but may be used outside it (for example, in a substitution method call):
'The cat sat in the hat'.gsub(/[csh]at/, '\0s') # => "The cats sats in the hats"
As seen above, a capture can be referred to by its number. A capture can also have a name, prefixed as ?<name>
or ?'name'
, and the name (symbolized) may be used as an index in MatchData[]
:
md = /\$(?<dollars>\d+)\.(?'cents'\d+)/.match("$3.67") # => #<MatchData "$3.67" dollars:"3" cents:"67"> md[:dollars] # => "3" md[:cents] # => "67" # The capture numbers are still valid. md[2] # => "67"
When a regexp contains a named capture, there are no unnamed captures:
/\$(?<dollars>\d+)\.(\d+)/.match("$3.67") # => #<MatchData "$3.67" dollars:"3">
A named group may be backreferenced as \k<name>
:
/(?<vowel>[aeiou]).\k<vowel>.\k<vowel>/.match('ototomy') # => #<MatchData "ototo" vowel:"o">
When (and only when) a regexp contains named capture groups and appears before the =~
operator, the captured substrings are assigned to local variables with corresponding names:
/\$(?<dollars>\d+)\.(?<cents>\d+)/ =~ '$3.67' dollars # => "3" cents # => "67"
Method Regexp#named_captures
returns a hash of the capture names and substrings; method Regexp#names
returns an array of the capture names.
A group may be made atomic with (?>
subexpression)
.
This causes the subexpression to be matched independently of the rest of the expression, so that the matched substring becomes fixed for the remainder of the match, unless the entire subexpression must be abandoned and subsequently revisited.
In this way subexpression is treated as a non-divisible whole. Atomic grouping is typically used to optimise patterns to prevent needless backtracking .
Example (without atomic grouping):
/".*"/.match('"Quote"') # => #<MatchData "\"Quote\"">
Analysis:
The leading subexpression "
in the pattern matches the first character "
in the target string.
The next subexpression .*
matches the next substring Quote“
(including the trailing double-quote).
Now there is nothing left in the target string to match the trailing subexpression "
in the pattern; this would cause the overall match to fail.
The matched substring is backtracked by one position: Quote
.
The final subexpression "
now matches the final substring "
, and the overall match succeeds.
If subexpression .*
is grouped atomically, the backtracking is disabled, and the overall match fails:
/"(?>.*)"/.match('"Quote"') # => nil
Atomic grouping can affect performance; see Atomic Group.
As seen above, a backreference number (\n
) or name (\k<name>
) gives access to a captured substring; the corresponding regexp subexpression may also be accessed, via the number (\gn
) or name (\g<name>
):
/\A(?<paren>\(\g<paren>*\))*\z/.match('(())') # ^1 # ^2 # ^3 # ^4 # ^5 # ^6 # ^7 # ^8 # ^9 # ^10
The pattern:
Matches at the beginning of the string, i.e. before the first character.
Enters a named group paren
.
Matches the first character in the string, '('
.
Calls the paren
group again, i.e. recurses back to the second step.
Re-enters the paren
group.
Matches the second character in the string, '('
.
Attempts to call paren
a third time, but fails because doing so would prevent an overall successful match.
Matches the third character in the string, ')'
; marks the end of the second recursive call
Matches the fourth character in the string, ')'
.
Matches the end of the string.
See Subexpression calls.
The conditional construct takes the form (?(cond)yes|no)
, where:
cond may be a capture number or name.
The match to be applied is yes if cond is captured; otherwise the match to be applied is no.
If not needed, |no
may be omitted.
Examples:
re = /\A(foo)?(?(1)(T)|(F))\z/ re.match('fooT') # => #<MatchData "fooT" 1:"foo" 2:"T" 3:nil> re.match('F') # => #<MatchData "F" 1:nil 2:nil 3:"F"> re.match('fooF') # => nil re.match('T') # => nil re = /\A(?<xyzzy>foo)?(?(<xyzzy>)(T)|(F))\z/ re.match('fooT') # => #<MatchData "fooT" xyzzy:"foo"> re.match('F') # => #<MatchData "F" xyzzy:nil> re.match('fooF') # => nil re.match('T') # => nil
The absence operator is a special group that matches anything which does not match the contained subexpressions.
/(?~real)/.match('surrealist') # => #<MatchData "surrea"> /(?~real)ist/.match('surrealist') # => #<MatchData "ealist"> /sur(?~real)ist/.match('surrealist') # => nil
The /\p{property_name}/
construct (with lowercase p
) matches characters using a Unicode property name, much like a character class; property Alpha
specifies alphabetic characters:
/\p{Alpha}/.match('a') # => #<MatchData "a"> /\p{Alpha}/.match('1') # => nil
A property can be inverted by prefixing the name with a caret character (^
):
/\p{^Alpha}/.match('1') # => #<MatchData "1"> /\p{^Alpha}/.match('a') # => nil
Or by using \P
(uppercase P
):
/\P{Alpha}/.match('1') # => #<MatchData "1"> /\P{Alpha}/.match('a') # => nil
See Unicode Properties for regexps based on the numerous properties.
Some commonly-used properties correspond to POSIX bracket expressions:
/\p{Alnum}/
: Alphabetic and numeric character
/\p{Alpha}/
: Alphabetic character
/\p{Blank}/
: Space or tab
/\p{Cntrl}/
: Control character
/\p{Digit}/
: Digit characters, and similar)
/\p{Lower}/
: Lowercase alphabetical character
/\p{Print}/
: Like \p{Graph}
, but includes the space character
/\p{Punct}/
: Punctuation character
/\p{Space}/
: Whitespace character ([:blank:]
, newline, carriage return, etc.)
/\p{Upper}/
: Uppercase alphabetical
/\p{XDigit}/
: Digit allowed in a hexadecimal number (i.e., 0-9a-fA-F)
These are also commonly used:
/\p{Emoji}/
: Unicode emoji.
/\p{Graph}/
: Characters excluding /\p{Cntrl}/
and /\p{Space}/
. Note that invisible characters under the Unicode “Format” category are included.
/\p{Word}/
: A member in one of these Unicode character categories (see below) or having one of these Unicode properties:
Unicode categories:
Mark
(M
).
Decimal Number
(Nd
)
Connector Punctuation
(Pc
).
Unicode properties:
Alpha
Join_Control
/\p{ASCII}/
: A character in the ASCII character set.
/\p{Any}/
: Any Unicode character (including unassigned characters).
/\p{Assigned}/
: An assigned character.
A Unicode character category name:
May be either its full name or its abbreviated name.
Is case-insensitive.
Treats a space, a hyphen, and an underscore as equivalent.
Examples:
/\p{lu}/ # => /\p{lu}/ /\p{LU}/ # => /\p{LU}/ /\p{Uppercase Letter}/ # => /\p{Uppercase Letter}/ /\p{Uppercase_Letter}/ # => /\p{Uppercase_Letter}/ /\p{UPPERCASE-LETTER}/ # => /\p{UPPERCASE-LETTER}/
Below are the Unicode character category abbreviations and names. Enumerations of characters in each category are at the links.
Letters:
L
, Letter
: LC
, Lm
, or Lo
.
LC
, Cased_Letter
: Ll
, Lt
, or Lu
.
Marks:
M
, Mark
: Mc
, Me
, or Mn
.
Numbers:
N
, Number
: Nd
, Nl
, or No
.
Punctuation:
P
, Punctuation
: Pc
, Pd
, Pe
, Pf
, Pi
, Po
, or Ps
.
S
, Symbol
: Sc
, Sk
, Sm
, or So
.
Z
, Separator
: Zl
, Zp
, or Zs
.
C
, Other
: Cc
, Cf
, Cn
, Co
, or Cs
.
Among the Unicode properties are:
A POSIX bracket expression is also similar to a character class. These expressions provide a portable alternative to the above, with the added benefit of encompassing non-ASCII characters:
/\d/
matches only ASCII decimal digits 0
through 9
.
/[[:digit:]]/
matches any character in the Unicode Decimal Number
(Nd
) category; see below.
The POSIX bracket expressions:
/[[:digit:]]/
: Matches a Unicode digit:
/[[:digit:]]/.match('9') # => #<MatchData "9"> /[[:digit:]]/.match("\u1fbf9") # => #<MatchData "9">
/[[:xdigit:]]/
: Matches a digit allowed in a hexadecimal number; equivalent to [0-9a-fA-F]
.
/[[:upper:]]/
: Matches a Unicode uppercase letter:
/[[:upper:]]/.match('A') # => #<MatchData "A"> /[[:upper:]]/.match("\u00c6") # => #<MatchData "Æ">
/[[:lower:]]/
: Matches a Unicode lowercase letter:
/[[:lower:]]/.match('a') # => #<MatchData "a"> /[[:lower:]]/.match("\u01fd") # => #<MatchData "ǽ">
/[[:alpha:]]/
: Matches /[[:upper:]]/
or /[[:lower:]]/
.
/[[:alnum:]]/
: Matches /[[:alpha:]]/
or /[[:digit:]]/
.
/[[:space:]]/
: Matches Unicode space character:
/[[:space:]]/.match(' ') # => #<MatchData " "> /[[:space:]]/.match("\u2005") # => #<MatchData " ">
/[[:blank:]]/
: Matches /[[:space:]]/
or tab character:
/[[:blank:]]/.match(' ') # => #<MatchData " "> /[[:blank:]]/.match("\u2005") # => #<MatchData " "> /[[:blank:]]/.match("\t") # => #<MatchData "\t">
/[[:cntrl:]]/
: Matches Unicode control character:
/[[:cntrl:]]/.match("\u0000") # => #<MatchData "\u0000"> /[[:cntrl:]]/.match("\u009f") # => #<MatchData "\u009F">
/[[:graph:]]/
: Matches any character except /[[:space:]]/
or /[[:cntrl:]]/
.
/[[:print:]]/
: Matches /[[:graph:]]/
or space character.
/[[:punct:]]/
: Matches any (Unicode punctuation character}[www.compart.com/en/unicode/category/Po]:
Ruby also supports these (non-POSIX) bracket expressions:
/[[:ascii:]]/
: Matches a character in the ASCII character set.
/[[:word:]]/
: Matches a character in one of these Unicode character categories or having one of these Unicode properties:
Unicode categories:
Mark
(M
).
Decimal Number
(Nd
)
Connector Punctuation
(Pc
).
Unicode properties:
Alpha
Join_Control
A comment may be included in a regexp pattern using the (?#
comment)
construct, where comment is a substring that is to be ignored. arbitrary text ignored by the regexp engine:
/foo(?#Ignore me)bar/.match('foobar') # => #<MatchData "foobar">
The comment may not include an unescaped terminator character.
See also Extended Mode.
Each of these modifiers sets a mode for the regexp:
i
: /pattern/i
sets Case-Insensitive Mode.
m
: /pattern/m
sets Multiline Mode.
x
: /pattern/x
sets Extended Mode.
o
: /pattern/o
sets Interpolation Mode.
Any, all, or none of these may be applied.
Modifiers i
, m
, and x
may be applied to subexpressions:
(?modifier)
turns the mode “on” for ensuing subexpressions
(?-modifier)
turns the mode “off” for ensuing subexpressions
(?modifier:subexp)
turns the mode “on” for subexp within the group
(?-modifier:subexp)
turns the mode “off” for subexp within the group
Example:
re = /(?i)te(?-i)st/ re.match('test') # => #<MatchData "test"> re.match('TEst') # => #<MatchData "TEst"> re.match('TEST') # => nil re.match('teST') # => nil re = /t(?i:e)st/ re.match('test') # => #<MatchData "test"> re.match('tEst') # => #<MatchData "tEst"> re.match('tEST') # => nil
Method Regexp#options
returns an integer whose value showing the settings for case-insensitivity mode, multiline mode, and extended mode.
By default, a regexp is case-sensitive:
/foo/.match('FOO') # => nil
Modifier i
enables case-insensitive mode:
/foo/i.match('FOO') # => #<MatchData "FOO">
Method Regexp#casefold?
returns whether the mode is case-insensitive.
The multiline-mode in Ruby is what is commonly called a “dot-all mode”:
Without the m
modifier, the subexpression .
does not match newlines:
/a.c/.match("a\nc") # => nil
With the modifier, it does match:
/a.c/m.match("a\nc") # => #<MatchData "a\nc">
Unlike other languages, the modifier m
does not affect the anchors ^
and $
. These anchors always match at line-boundaries in Ruby.
Modifier x
enables extended mode, which means that:
Literal white space in the pattern is to be ignored.
Character #
marks the remainder of its containing line as a comment, which is also to be ignored for matching purposes.
In extended mode, whitespace and comments may be used to form a self-documented regexp.
Regexp
not in extended mode (matches some Roman numerals):
pattern = '^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$' re = /#{pattern}/ re.match('MCMXLIII') # => #<MatchData "MCMXLIII" 1:"CM" 2:"XL" 3:"III">
Regexp
in extended mode:
pattern = <<-EOT ^ # beginning of string M{0,3} # thousands - 0 to 3 Ms (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 Cs), # or 500-800 (D, followed by 0 to 3 Cs) (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 Xs), # or 50-80 (L, followed by 0 to 3 Xs) (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 Is), # or 5-8 (V, followed by 0 to 3 Is) $ # end of string EOT re = /#{pattern}/x re.match('MCMXLIII') # => #<MatchData "MCMXLIII" 1:"CM" 2:"XL" 3:"III">
Modifier o
means that the first time a literal regexp with interpolations is encountered, the generated Regexp
object is saved and used for all future evaluations of that literal regexp. Without modifier o
, the generated Regexp
is not saved, so each evaluation of the literal regexp generates a new Regexp
object.
Without modifier o
:
def letters; sleep 5; /[A-Z][a-z]/; end words = %w[abc def xyz] start = Time.now words.each {|word| word.match(/\A[#{letters}]+\z/) } Time.now - start # => 15.0174892
With modifier o
:
start = Time.now words.each {|word| word.match(/\A[#{letters}]+\z/o) } Time.now - start # => 5.0010866
Note that if the literal regexp does not have interpolations, the o
behavior is the default.
By default, a regexp with only US-ASCII characters has US-ASCII encoding:
re = /foo/ re.source.encoding # => #<Encoding:US-ASCII> re.encoding # => #<Encoding:US-ASCII>
A regular expression containing non-US-ASCII characters is assumed to use the source encoding. This can be overridden with one of the following modifiers.
/pat/n
: US-ASCII if only containing US-ASCII characters, otherwise ASCII-8BIT:
/foo/n.encoding # => #<Encoding:US-ASCII> /foo\xff/n.encoding # => #<Encoding:ASCII-8BIT> /foo\x7f/n.encoding # => #<Encoding:US-ASCII>
/pat/u
: UTF-8
/foo/u.encoding # => #<Encoding:UTF-8>
/pat/e
: EUC-JP
/foo/e.encoding # => #<Encoding:EUC-JP>
/pat/s
: Windows-31J
/foo/s.encoding # => #<Encoding:Windows-31J>
A regexp can be matched against a target string when either:
They have the same encoding.
The regexp’s encoding is a fixed encoding and the string contains only ASCII characters. Method
Regexp#fixed_encoding?
returns whether the regexp has a fixed encoding.
If a match between incompatible encodings is attempted an Encoding::CompatibilityError
exception is raised.
Example:
re = eval("# encoding: ISO-8859-1\n/foo\\xff?/") re.encoding # => #<Encoding:ISO-8859-1> re =~ "foo".encode("UTF-8") # => 0 re =~ "foo\u0100" # Raises Encoding::CompatibilityError
The encoding may be explicitly fixed by including Regexp::FIXEDENCODING
in the second argument for Regexp.new
:
# Regexp with encoding ISO-8859-1. re = Regexp.new("a".force_encoding('iso-8859-1'), Regexp::FIXEDENCODING) re.encoding # => #<Encoding:ISO-8859-1> # Target string with encoding UTF-8. s = "a\u3042" s.encoding # => #<Encoding:UTF-8> re.match(s) # Raises Encoding::CompatibilityError.
When either a regexp source or a target string comes from untrusted input, malicious values could become a denial-of-service attack; to prevent such an attack, it is wise to set a timeout.
Regexp has two timeout values:
A class default timeout, used for a regexp whose instance timeout is nil
; this default is initially nil
, and may be set by method Regexp.timeout=
:
Regexp.timeout # => nil Regexp.timeout = 3.0 Regexp.timeout # => 3.0
An instance timeout, which defaults to nil
and may be set in Regexp.new
:
re = Regexp.new('foo', timeout: 5.0) re.timeout # => 5.0
When regexp.timeout is nil
, the timeout “falls through” to Regexp.timeout
; when regexp.timeout is non-nil
, that value controls timing out:
| regexp.timeout Value | Regexp.timeout Value | Result | |----------------------|----------------------|-----------------------------| | nil | nil | Never times out. | | nil | Float | Times out in Float seconds. | | Float | Any | Times out in Float seconds. |
For certain values of the pattern and target string, matching time can grow polynomially or exponentially in relation to the input size; the potential vulnerability arising from this is the regular expression denial-of-service (ReDoS) attack.
Regexp matching can apply an optimization to prevent ReDoS attacks. When the optimization is applied, matching time increases linearly (not polynomially or exponentially) in relation to the input size, and a ReDoS attach is not possible.
This optimization is applied if the pattern meets these criteria:
No backreferences.
No subexpression calls.
No nested lookaround anchors or atomic groups.
No nested quantifiers with counting (i.e. no nested {n}
, {min,}
, {,max}
, or {min,max}
style quantifiers)
You can use method Regexp.linear_time?
to determine whether a pattern meets these criteria:
Regexp.linear_time?(/a*/) # => true Regexp.linear_time?('a*') # => true Regexp.linear_time?(/(a*)\1/) # => false
However, an untrusted source may not be safe even if the method returns true
, because the optimization uses memoization (which may invoke large memory consumption).
Read (online PDF books):
Mastering Regular Expressions by Jeffrey E.F. Friedl.
Regular Expressions Cookbook by Jan Goyvaerts & Steven Levithan.
Explore, test (interactive online editor):
TCPServer
represents a TCP/IP server socket.
A simple TCP server may look like:
require 'socket' server = TCPServer.new 2000 # Server bind to port 2000 loop do client = server.accept # Wait for a client to connect client.puts "Hello !" client.puts "Time is #{Time.now}" client.close end
A more usable server (serving multiple clients):
require 'socket' server = TCPServer.new 2000 loop do Thread.start(server.accept) do |client| client.puts "Hello !" client.puts "Time is #{Time.now}" client.close end end
UNIXServer
represents a UNIX domain stream server socket.
This class implements a pretty printing algorithm. It finds line breaks and nice indentations for grouped structure.
By default, the class assumes that primitive elements are strings and each byte in the strings have single column in width. But it can be used for other situations by giving suitable arguments for some methods:
newline object and space generation block for PrettyPrint.new
optional width argument for PrettyPrint#text
There are several candidate uses:
text formatting using proportional fonts
multibyte characters which has columns different to number of bytes
non-string formatting
Box based formatting?
Other (better) model/algorithm?
Report any bugs at bugs.ruby-lang.org
Christian Lindig, Strictly Pretty, March 2000, lindig.github.io/papers/strictly-pretty-2000.pdf
Philip Wadler, A prettier printer, March 1998, homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier
Tanaka Akira <akr@fsij.org>
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.
A utility class for managing temporary files.
There are two kind of methods of creating a temporary file:
Tempfile.create
(recommended)
Tempfile.new
and Tempfile.open
(mostly for backward compatibility, not recommended)
Tempfile.create
creates a usual File object. The timing of file deletion is predictable. Also, it supports open-and-unlink technique which removes the temporary file immediately after creation.
Tempfile.new
and Tempfile.open
creates a Tempfile object. The created file is removed by the GC
(finalizer). The timing of file deletion is not predictable.
require 'tempfile' # Tempfile.create with a block # The filename are choosen automatically. # (You can specify the prefix and suffix of the filename by an optional argument.) Tempfile.create {|f| f.puts "foo" f.rewind f.read # => "foo\n" } # The file is removed at block exit. # Tempfile.create without a block # You need to unlink the file in non-block form. f = Tempfile.create f.puts "foo" f.close File.unlink(f.path) # You need to unlink the file. # Tempfile.create(anonymous: true) without a block f = Tempfile.create(anonymous: true) # The file is already removed because anonymous. f.path # => "/tmp/" (no filename since no file) f.puts "foo" f.rewind f.read # => "foo\n" f.close # Tempfile.create(anonymous: true) with a block Tempfile.create(anonymous: true) {|f| # The file is already removed because anonymous. f.path # => "/tmp/" (no filename since no file) f.puts "foo" f.rewind f.read # => "foo\n" } # Not recommended: Tempfile.new without a block file = Tempfile.new('foo') file.path # => A unique filename in the OS's temp directory, # e.g.: "/tmp/foo.24722.0" # This filename contains 'foo' in its basename. file.write("hello world") file.rewind file.read # => "hello world" file.close file.unlink # deletes the temp file
Tempfile.new
and Tempfile.open
This section does not apply to Tempfile.create
because it returns a File
object (not a Tempfile
object).
When you create a Tempfile
object, it will create a temporary file with a unique filename. A Tempfile
objects behaves just like a File
object, and you can perform all the usual file operations on it: reading data, writing data, changing its permissions, etc. So although this class does not explicitly document all instance methods supported by File
, you can in fact call any File
instance method on a Tempfile
object.
A Tempfile
object has a finalizer to remove the temporary file. This means that the temporary file is removed via GC
. This can cause several problems:
Long GC
intervals and conservative GC
can accumulate temporary files that are not removed.
Temporary files are not removed if Ruby exits abnormally (such as SIGKILL, SEGV).
There are legacy good practices for Tempfile.new
and Tempfile.open
as follows.
When a Tempfile
object is garbage collected, or when the Ruby interpreter exits, its associated temporary file is automatically deleted. This means that it’s unnecessary to explicitly delete a Tempfile
after use, though it’s a good practice to do so: not explicitly deleting unused Tempfiles can potentially leave behind a large number of temp files on the filesystem until they’re garbage collected. The existence of these temp files can make it harder to determine a new Tempfile
filename.
Therefore, one should always call unlink
or close in an ensure block, like this:
file = Tempfile.new('foo') begin # ...do something with file... ensure file.close file.unlink # deletes the temp file end
Tempfile.create
{ … } exists for this purpose and is more convenient to use. Note that Tempfile.create
returns a File
instance instead of a Tempfile
, which also avoids the overhead and complications of delegation.
Tempfile.create('foo') do |file| # ...do something with file... end
On POSIX systems, it’s possible to unlink a file right after creating it, and before closing it. This removes the filesystem entry without closing the file handle, so it ensures that only the processes that already had the file handle open can access the file’s contents. It’s strongly recommended that you do this if you do not want any other processes to be able to read from or write to the Tempfile
, and you do not need to know the Tempfile’s filename either.
Also, this guarantees the temporary file is removed even if Ruby exits abnormally. The OS reclaims the storage for the temporary file when the file is closed or the Ruby process exits (normally or abnormally).
For example, a practical use case for unlink-after-creation would be this: you need a large byte buffer that’s too large to comfortably fit in RAM, e.g. when you’re writing a web server and you want to buffer the client’s file upload data.
‘Tempfile.create(anonymous: true)` supports this behavior. It also works on Windows.
Tempfile’s filename picking method is both thread-safe and inter-process-safe: it guarantees that no other threads or processes will pick the same filename.
Tempfile
itself however may not be entirely thread-safe. If you access the same Tempfile
object from multiple threads then you should protect it with a mutex.
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 given an invalid regexp expression.
Regexp.new("?")
raises the exception:
RegexpError: target of repeat operator is not specified: /?/
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.
RubyGems is the Ruby standard for publishing and managing third party libraries.
For user documentation, see:
gem help
and gem help [command]
For gem developer documentation see:
Gem::Version
for version dependency notes
Further RubyGems documentation can be found at:
RubyGems API (also available from gem server
)
RubyGems will load plugins in the latest version of each installed gem or $LOAD_PATH. Plugins must be named ‘rubygems_plugin’ (.rb, .so, etc) and placed at the root of your gem’s require_path. Plugins are installed at a special location and loaded on boot.
For an example plugin, see the Graph gem which adds a gem graph
command.
RubyGems defaults are stored in lib/rubygems/defaults.rb. If you’re packaging RubyGems or implementing Ruby you can change RubyGems’ defaults.
For RubyGems packagers, provide lib/rubygems/defaults/operating_system.rb and override any defaults from lib/rubygems/defaults.rb.
For Ruby implementers, provide lib/rubygems/defaults/#{RUBY_ENGINE}.rb and override any defaults from lib/rubygems/defaults.rb.
If you need RubyGems to perform extra work on install or uninstall, your defaults override file can set pre/post install and uninstall hooks. See Gem::pre_install
, Gem::pre_uninstall
, Gem::post_install
, Gem::post_uninstall
.
You can submit bugs to the RubyGems bug tracker on GitHub
RubyGems is currently maintained by Eric Hodel.
RubyGems was originally developed at RubyConf 2003 by:
Rich Kilmer – rich(at)infoether.com
Chad Fowler – chad(at)chadfowler.com
David Black – dblack(at)wobblini.net
Paul Brannan – paul(at)atdesk.com
Jim Weirich – jim(at)weirichhouse.org
Contributors:
Gavin Sinclair – gsinclair(at)soyabean.com.au
George Marrows – george.marrows(at)ntlworld.com
Dick Davies – rasputnik(at)hellooperator.net
Mauricio Fernandez – batsman.geo(at)yahoo.com
Simon Strandgaard – neoneye(at)adslhome.dk
Dave Glasser – glasser(at)mit.edu
Paul Duncan – pabs(at)pablotron.org
Ville Aine – vaine(at)cs.helsinki.fi
Eric Hodel – drbrain(at)segment7.net
Daniel Berger – djberg96(at)gmail.com
Phil Hagelberg – technomancy(at)gmail.com
Ryan Davis – ryand-ruby(at)zenspider.com
Evan Phoenix – evan(at)fallingsnow.net
Steve Klabnik – steve(at)steveklabnik.com
(If your name is missing, PLEASE let us know!)
See LICENSE.txt for permissions.
Thanks!
-The RubyGems Team
Provides 3 methods for declaring when something is going away.
+deprecate(name, repl, year, month)+:
Indicate something may be removed on/after a certain date.
+rubygems_deprecate(name, replacement=:none)+:
Indicate something will be removed in the next major RubyGems version, and (optionally) a replacement for it.
rubygems_deprecate_command
:
Indicate a RubyGems command (in +lib/rubygems/commands/*.rb+) will be removed in the next RubyGems version.
Also provides skip_during
for temporarily turning off deprecation warnings. This is intended to be used in the test suite, so deprecation warnings don’t cause test failures if you need to make sure stderr is otherwise empty.
Example usage of deprecate
and rubygems_deprecate
:
class Legacy def self.some_class_method # ... end def some_instance_method # ... end def some_old_method # ... end extend Gem::Deprecate deprecate :some_instance_method, "X.z", 2011, 4 rubygems_deprecate :some_old_method, "Modern#some_new_method" class << self extend Gem::Deprecate deprecate :some_class_method, :none, 2011, 4 end end
Example usage of rubygems_deprecate_command
:
class Gem::Commands::QueryCommand < Gem::Command extend Gem::Deprecate rubygems_deprecate_command # ... end
Example usage of skip_during
:
class TestSomething < Gem::Testcase def test_some_thing_with_deprecations Gem::Deprecate.skip_during do actual_stdout, actual_stderr = capture_output do Gem.something_deprecated end assert_empty actual_stdout assert_equal(expected, actual_stderr) end end end
mkmf.rb is used by Ruby C extensions to generate a Makefile which will correctly compile and link the C extension to Ruby and a third-party library.
This library is an interface to secure random number generators which are suitable for generating session keys in HTTP cookies, etc.
You can use this library in your application by requiring it:
require 'securerandom'
It supports the following secure random number generators:
openssl
/dev/urandom
SecureRandom
is extended by the Random::Formatter
module which defines the following methods:
alphanumeric
base64
choose
gen_random
hex
rand
random_bytes
random_number
urlsafe_base64
uuid
These methods are usable as class methods of SecureRandom
such as SecureRandom.hex
.
If a secure random number generator is not available, NotImplementedError
is raised.
FIXME: This isn’t documented in Nutshell.
Since MonitorMixin.new_cond
returns a ConditionVariable
, and the example above calls while_wait and signal, this class should be documented.
Subclass of StreamUI that instantiates the user interaction using $stdin, $stdout, and $stderr.
ConditionVariable
objects augment class Mutex
. Using condition variables, it is possible to suspend while in the middle of a critical section until a resource becomes available.
Example:
mutex = Thread::Mutex.new resource = Thread::ConditionVariable.new a = Thread.new { mutex.synchronize { # Thread 'a' now needs the resource resource.wait(mutex) # 'a' can now have the resource } } b = Thread.new { mutex.synchronize { # Thread 'b' has finished using the resource resource.signal } }