A Float object represents a sometimes-inexact real number using the native architecture’s double-precision floating point representation.
Floating point has a different arithmetic and is an inexact number. So you should know its esoteric system. See following:
You can create a Float object explicitly with:
A floating-point literal.
You can convert certain objects to Floats with:
Method Float
.
First, what’s elsewhere. Class Float:
Inherits from class Numeric.
Here, class Float provides methods for:
finite?
: Returns whether self
is finite.
hash
: Returns the integer hash code for self
.
infinite?
: Returns whether self
is infinite.
nan?
: Returns whether self
is a NaN (not-a-number).
<
: Returns whether self
is less than the given value.
<=
: Returns whether self
is less than or equal to the given value.
<=>
: Returns a number indicating whether self
is less than, equal to, or greater than the given value.
==
(aliased as ===
and eql?
): Returns whether self
is equal to the given value.
>
: Returns whether self
is greater than the given value.
>=
: Returns whether self
is greater than or equal to the given value.
*
: Returns the product of self
and the given value.
**
: Returns the value of self
raised to the power of the given value.
+
: Returns the sum of self
and the given value.
-
: Returns the difference of self
and the given value.
/
: Returns the quotient of self
and the given value.
ceil
: Returns the smallest number greater than or equal to self
.
coerce
: Returns a 2-element array containing the given value converted to a Float and self
divmod
: Returns a 2-element array containing the quotient and remainder results of dividing self
by the given value.
fdiv
: Returns the Float
result of dividing self
by the given value.
floor
: Returns the greatest number smaller than or equal to self
.
next_float
: Returns the next-larger representable Float.
prev_float
: Returns the next-smaller representable Float.
quo
: Returns the quotient from dividing self
by the given value.
round
: Returns self
rounded to the nearest value, to a given precision.
to_i
(aliased as to_int
): Returns self
truncated to an Integer
.
to_s
(aliased as inspect
): Returns a string containing the place-value representation of self
in the given radix.
truncate
: Returns self
truncated to a given precision.
Fibers are primitives for implementing light weight cooperative concurrency in Ruby. Basically they are a means of creating code blocks that can be paused and resumed, much like threads. The main difference is that they are never preempted and that the scheduling must be done by the programmer and not the VM.
As opposed to other stackless light weight concurrency models, each fiber comes with a stack. This enables the fiber to be paused from deeply nested function calls within the fiber block. See the ruby(1) manpage to configure the size of the fiber stack(s).
When a fiber is created it will not run automatically. Rather it must be explicitly asked to run using the Fiber#resume
method. The code running inside the fiber can give up control by calling Fiber.yield
in which case it yields control back to caller (the caller of the Fiber#resume
).
Upon yielding or termination the Fiber
returns the value of the last executed expression
For instance:
fiber = Fiber.new do Fiber.yield 1 2 end puts fiber.resume puts fiber.resume puts fiber.resume
produces
1 2 FiberError: dead fiber called
The Fiber#resume
method accepts an arbitrary number of parameters, if it is the first call to resume
then they will be passed as block arguments. Otherwise they will be the return value of the call to Fiber.yield
Example:
fiber = Fiber.new do |first| second = Fiber.yield first + 2 end puts fiber.resume 10 puts fiber.resume 1_000_000 puts fiber.resume "The fiber will be dead before I can cause trouble"
produces
12 1000000 FiberError: dead fiber called
The concept of non-blocking fiber was introduced in Ruby 3.0. A non-blocking fiber, when reaching a operation that would normally block the fiber (like sleep
, or wait for another process or I/O) will yield control to other fibers and allow the scheduler to handle blocking and waking up (resuming) this fiber when it can proceed.
For a Fiber
to behave as non-blocking, it need to be created in Fiber.new
with blocking: false
(which is the default), and Fiber.scheduler
should be set with Fiber.set_scheduler
. If Fiber.scheduler
is not set in the current thread, blocking and non-blocking fibers’ behavior is identical.
Ruby doesn’t provide a scheduler class: it is expected to be implemented by the user and correspond to Fiber::Scheduler
.
There is also Fiber.schedule
method, which is expected to immediately perform the given block in a non-blocking manner. Its actual implementation is up to the scheduler.
A class which allows both internal and external iteration.
An Enumerator
can be created by the following methods.
Most methods have two forms: a block form where the contents are evaluated for each item in the enumeration, and a non-block form which returns a new Enumerator
wrapping the iteration.
enumerator = %w(one two three).each puts enumerator.class # => Enumerator enumerator.each_with_object("foo") do |item, obj| puts "#{obj}: #{item}" end # foo: one # foo: two # foo: three enum_with_obj = enumerator.each_with_object("foo") puts enum_with_obj.class # => Enumerator enum_with_obj.each do |item, obj| puts "#{obj}: #{item}" end # foo: one # foo: two # foo: three
This allows you to chain Enumerators together. For example, you can map a list’s elements to strings containing the index and the element as a string via:
puts %w[foo bar baz].map.with_index { |w, i| "#{i}:#{w}" } # => ["0:foo", "1:bar", "2:baz"] == External Iteration
An Enumerator
can also be used as an external iterator. For example, Enumerator#next
returns the next value of the iterator or raises StopIteration
if the Enumerator
is at the end.
e = [1,2,3].each # returns an enumerator object. puts e.next # => 1 puts e.next # => 2 puts e.next # => 3 puts e.next # raises StopIteration
next
, next_values
, peek
and peek_values
are the only methods which use external iteration (and Array#zip(Enumerable-not-Array)
which uses next
).
These methods do not affect other internal enumeration methods, unless the underlying iteration method itself has side-effect, e.g. IO#each_line
.
External iteration differs significantly from internal iteration due to using a Fiber:
- The Fiber adds some overhead compared to internal enumeration. - The stacktrace will only include the stack from the Enumerator, not above. - Fiber-local variables are *not* inherited inside the Enumerator Fiber, which instead starts with no Fiber-local variables. - Fiber storage variables *are* inherited and are designed to handle Enumerator Fibers. Assigning to a Fiber storage variable only affects the current Fiber, so if you want to change state in the caller Fiber of the Enumerator Fiber, you need to use an extra indirection (e.g., use some object in the Fiber storage variable and mutate some ivar of it).
Concretely:
Thread.current[:fiber_local] = 1 Fiber[:storage_var] = 1 e = Enumerator.new do |y| p Thread.current[:fiber_local] # for external iteration: nil, for internal iteration: 1 p Fiber[:storage_var] # => 1, inherited Fiber[:storage_var] += 1 y << 42 end p e.next # => 42 p Fiber[:storage_var] # => 1 (it ran in a different Fiber) e.each { p _1 } p Fiber[:storage_var] # => 2 (it ran in the same Fiber/"stack" as the current Fiber) == Convert External Iteration to Internal Iteration
You can use an external iterator to implement an internal iterator as follows:
def ext_each(e) while true begin vs = e.next_values rescue StopIteration return $!.result end y = yield(*vs) e.feed y end end o = Object.new def o.each puts yield puts yield(1) puts yield(1, 2) 3 end # use o.each as an internal iterator directly. puts o.each {|*x| puts x; [:b, *x] } # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3 # convert o.each to an external iterator for # implementing an internal iterator. puts ext_each(o.to_enum) {|*x| puts x; [:b, *x] } # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3
Raised to stop the iteration, in particular by Enumerator#next
. It is rescued by Kernel#loop
.
loop do puts "Hello" raise StopIteration puts "World" end puts "Done!"
produces:
Hello Done!
Raised when the interrupt signal is received, typically because the user has pressed Control-C (on most posix platforms). As such, it is a subclass of SignalException
.
begin puts "Press ctrl-C when you get bored" loop {} rescue Interrupt => e puts "Note: You will typically use Signal.trap instead." end
produces:
Press ctrl-C when you get bored
then waits until it is interrupted with Control-C and then prints:
Note: You will typically use Signal.trap instead.
The most standard error types are subclasses of StandardError
. A rescue clause without an explicit Exception
class will rescue all StandardErrors (and only those).
def foo raise "Oups" end foo rescue "Hello" #=> "Hello"
On the other hand:
require 'does/not/exist' rescue "Hi"
raises the exception:
LoadError: no such file to load -- does/not/exist
Raised when encountering an object that is not of the expected type.
[1, 2, 3].first("two")
raises the exception:
TypeError: no implicit conversion of String into Integer
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 the given index is invalid.
a = [:foo, :bar] a.fetch(0) #=> :foo a[4] #=> nil a.fetch(4) #=> IndexError: index 4 outside of array bounds: -2...2
Raised when the specified key is not found. It is a subclass of IndexError
.
h = {"foo" => :bar} h.fetch("foo") #=> :bar h.fetch("baz") #=> KeyError: key not found: "baz"
ScriptError
is the superclass for errors raised when a script can not be executed because of a LoadError
, NotImplementedError
or a SyntaxError
. Note these type of ScriptErrors
are not StandardError
and will not be rescued unless it is specified explicitly (or its ancestor Exception
).
Raised when encountering Ruby code with an invalid syntax.
eval("1+1=2")
raises the exception:
SyntaxError: (eval):1: syntax error, unexpected '=', expecting $end
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
.
Raised when a given name is invalid or undefined.
puts foo
raises the exception:
NameError: undefined local variable or method `foo' for main:Object
Since constant names must start with a capital:
Integer.const_set :answer, 42
raises the exception:
NameError: wrong constant name answer
Raised when a method is called on a receiver which doesn’t have it defined and also fails to respond with method_missing
.
"hello".to_ary
raises the exception:
NoMethodError: undefined method `to_ary' for "hello":String
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 there is an attempt to modify a frozen object.
[1, 2, 3].freeze << 4
raises the exception:
FrozenError: can't modify frozen Array
No longer used by internal code.
Raised when memory allocation fails.
SystemCallError
is the base class for all low-level platform-dependent errors.
The errors available on the current platform are subclasses of SystemCallError
and are defined in the Errno
module.
File.open("does/not/exist")
raises the exception:
Errno::ENOENT: No such file or directory - does/not/exist
A Range object represents a collection of values that are between given begin and end values.
You can create an Range object explicitly with:
A range literal:
# Ranges that use '..' to include the given end value. (1..4).to_a # => [1, 2, 3, 4] ('a'..'d').to_a # => ["a", "b", "c", "d"] # Ranges that use '...' to exclude the given end value. (1...4).to_a # => [1, 2, 3] ('a'...'d').to_a # => ["a", "b", "c"]
A range may be created using method Range.new
:
# Ranges that by default include the given end value. Range.new(1, 4).to_a # => [1, 2, 3, 4] Range.new('a', 'd').to_a # => ["a", "b", "c", "d"] # Ranges that use third argument +exclude_end+ to exclude the given end value. Range.new(1, 4, true).to_a # => [1, 2, 3] Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
A beginless range has a definite end value, but a nil
begin value. Such a range includes all values up to the end value.
r = (..4) # => nil..4 r.begin # => nil r.include?(-50) # => true r.include?(4) # => true r = (...4) # => nil...4 r.include?(4) # => false Range.new(nil, 4) # => nil..4 Range.new(nil, 4, true) # => nil...4
A beginless range may be used to slice an array:
a = [1, 2, 3, 4] r = (..2) # => nil...2 a[r] # => [1, 2]
Method each
for a beginless range raises an exception.
An endless range has a definite begin value, but a nil
end value. Such a range includes all values from the begin value.
r = (1..) # => 1.. r.end # => nil r.include?(50) # => true Range.new(1, nil) # => 1..
The literal for an endless range may be written with either two dots or three. The range has the same elements, either way. But note that the two are not equal:
r0 = (1..) # => 1.. r1 = (1...) # => 1... r0.begin == r1.begin # => true r0.end == r1.end # => true r0 == r1 # => false
An endless range may be used to slice an array:
a = [1, 2, 3, 4] r = (2..) # => 2.. a[r] # => [3, 4]
Method each
for an endless range calls the given block indefinitely:
a = [] r = (1..) r.each do |i| a.push(i) if i.even? break if i > 10 end a # => [2, 4, 6, 8, 10]
A range can be both beginless and endless. For literal beginless, endless ranges, at least the beginning or end of the range must be given as an explicit nil value. It is recommended to use an explicit nil beginning and implicit nil end, since that is what Ruby uses for Range#inspect
:
(nil..) # => (nil..) (..nil) # => (nil..) (nil..nil) # => (nil..)
An object may be put into a range if its class implements instance method <=>
. Ruby core classes that do so include Array
, Complex
, File::Stat
, Float
, Integer
, Kernel
, Module
, Numeric
, Rational
, String
, Symbol
, and Time
.
Example:
t0 = Time.now # => 2021-09-19 09:22:48.4854986 -0500 t1 = Time.now # => 2021-09-19 09:22:56.0365079 -0500 t2 = Time.now # => 2021-09-19 09:23:08.5263283 -0500 (t0..t2).include?(t1) # => true (t0..t1).include?(t2) # => false
A range can be iterated over only if its elements implement instance method succ
. Ruby core classes that do so include Integer
, String
, and Symbol
(but not the other classes mentioned above).
Iterator methods include:
Included from module Enumerable: each_entry
, each_with_index
, each_with_object
, each_slice
, each_cons
, and reverse_each
.
Example:
a = [] (1..4).each {|i| a.push(i) } a # => [1, 2, 3, 4]
A user-defined class that is to be used in a range must implement instance <=>
; see Integer#<=>
. To make iteration available, it must also implement instance method succ
; see Integer#succ
.
The class below implements both <=>
and succ
, and so can be used both to construct ranges and to iterate over them. Note that the Comparable
module is included so the ==
method is defined in terms of <=>
.
# Represent a string of 'X' characters. class Xs include Comparable attr_accessor :length def initialize(n) @length = n end def succ Xs.new(@length + 1) end def <=>(other) @length <=> other.length end def to_s sprintf "%2d #{inspect}", @length end def inspect 'X' * @length end end r = Xs.new(3)..Xs.new(6) #=> XXX..XXXXXX r.to_a #=> [XXX, XXXX, XXXXX, XXXXXX] r.include?(Xs.new(5)) #=> true r.include?(Xs.new(7)) #=> false
First, what’s elsewhere. Class Range:
Inherits from class Object.
Includes module Enumerable, which provides dozens of additional methods.
Here, class Range provides methods that are useful for:
::new
: Returns a new range.
begin
: Returns the begin value given for self
.
bsearch
: Returns an element from self
selected by a binary search.
count
: Returns a count of elements in self
.
end
: Returns the end value given for self
.
exclude_end?
: Returns whether the end object is excluded.
first
: Returns the first elements of self
.
hash
: Returns the integer hash code.
last
: Returns the last elements of self
.
max
: Returns the maximum values in self
.
min
: Returns the minimum values in self
.
minmax
: Returns the minimum and maximum values in self
.
size
: Returns the count of elements in self
.
==
: Returns whether a given object is equal to self
(uses ==
).
===
: Returns whether the given object is between the begin and end values.
cover?
: Returns whether a given object is within self
.
eql?
: Returns whether a given object is equal to self
(uses eql?
).
include?
(aliased as member?
): Returns whether a given object is an element of self
.
%
: Requires argument n
; calls the block with each n
-th element of self
.
each
: Calls the block with each element of self
.
step
: Takes optional argument n
(defaults to 1); calls the block with each n
-th element of self
.
Regular expressions (regexps) are patterns which describe the contents of a string. They’re used for testing whether a string contains a given pattern, or extracting the portions that match. They are created with the /
pat/
and %r{
pat}
literals or the Regexp.new
constructor.
A regexp is usually delimited with forward slashes (/
). For example:
/hay/ =~ 'haystack' #=> 0 /y/.match('haystack') #=> #<MatchData "y">
If a string contains the pattern it is said to match. A literal string matches itself.
Here ‘haystack’ does not contain the pattern ‘needle’, so it doesn’t match:
/needle/.match('haystack') #=> nil
Here ‘haystack’ contains the pattern ‘hay’, so it matches:
/hay/.match('haystack') #=> #<MatchData "hay">
Specifically, /st/
requires that the string contains the letter s followed by the letter t, so it matches haystack, also.
Note that any Regexp
matching will raise a RuntimeError
if timeout is set and exceeded. See “Timeout” section in detail.
A regexp may contain interpolated strings; trivially:
foo = 'bar' /#{foo}/ # => /bar/
=~
and Regexp#match
Pattern matching may be achieved by using =~
operator or Regexp#match
method.
=~
Operator =~
is Ruby’s basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp
and String
so the order of String
and Regexp
do not matter. Other classes may have different implementations of =~
.) If a match is found, the operator returns index of first match in string, otherwise it returns nil
.
/hay/ =~ 'haystack' #=> 0 'haystack' =~ /hay/ #=> 0 /a/ =~ 'haystack' #=> 1 /u/ =~ 'haystack' #=> nil
Using =~
operator with a String
and Regexp
the $~
global variable is set after a successful match. $~
holds a MatchData
object. Regexp.last_match
is equivalent to $~
.
Regexp#match
Method
The match
method returns a MatchData
object:
/st/.match('haystack') #=> #<MatchData "st">
The following are metacharacters (
, )
, [
, ]
, {
, }
, .
, ?
, +
, *
. They have a specific meaning when appearing in a pattern. To match them literally they must be backslash-escaped. To match a backslash literally, backslash-escape it: \\
.
/1 \+ 2 = 3\?/.match('Does 1 + 2 = 3?') #=> #<MatchData "1 + 2 = 3?"> /a\\\\b/.match('a\\\\b') #=> #<MatchData "a\\b">
Patterns behave like double-quoted strings and can contain the same backslash escapes (the meaning of \s
is different, however, see below).
/\s\u{6771 4eac 90fd}/.match("Go to 東京都") #=> #<MatchData " 東京都">
Arbitrary Ruby expressions can be embedded into patterns with the #{...}
construct.
place = "東京都" /#{place}/.match("Go to 東京都") #=> #<MatchData "東京都">
A character class is delimited with square brackets ([
, ]
) and lists characters that may appear at that point in the match. /[ab]/
means a or b, as opposed to /ab/
which means a followed by b.
/W[aeiou]rd/.match("Word") #=> #<MatchData "Word">
Within a character class the hyphen (-
) is a metacharacter denoting an inclusive range of characters. [abcd]
is equivalent to [a-d]
. A range can be followed by another range, so [abcdwxyz]
is equivalent to [a-dw-z]
. The order in which ranges or individual characters appear inside a character class is irrelevant.
/[0-9a-f]/.match('9f') #=> #<MatchData "9"> /[9f]/.match('9f') #=> #<MatchData "9">
If the first character of a character class is a caret (^
) the class is inverted: it matches any character except those named.
/[^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]/
The following metacharacters also behave like character classes:
/./
- Any character except a newline.
/./m
- Any character (the m
modifier enables multiline mode)
/\w/
- A word character ([a-zA-Z0-9_]
)
/\W/
- A non-word character ([^a-zA-Z0-9_]
). Please take a look at Bug #4044 if using /\W/
with the /i
modifier.
/\d/
- A digit character ([0-9]
)
/\D/
- A non-digit character ([^0-9]
)
/\h/
- A hexdigit character ([0-9a-fA-F]
)
/\H/
- A non-hexdigit character ([^0-9a-fA-F]
)
/\s/
- A whitespace character: /[ \t\r\n\f\v]/
/\S/
- A non-whitespace character: /[^ \t\r\n\f\v]/
/\R/
- A linebreak: \n
, \v
, \f
, \r
\u0085
(NEXT LINE), \u2028
(LINE SEPARATOR), \u2029
(PARAGRAPH SEPARATOR) or \r\n
.
POSIX bracket expressions are also similar to character classes. They provide a portable alternative to the above, with the added benefit that they encompass non-ASCII characters. For instance, /\d/
matches only the ASCII decimal digits (0-9); whereas /[[:digit:]]/
matches any character in the Unicode Nd category.
/[[:alnum:]]/
- Alphabetic and numeric character
/[[:alpha:]]/
- Alphabetic character
/[[:blank:]]/
- Space or tab
/[[:cntrl:]]/
- Control character
/[[:digit:]]/
- Digit
/[[:graph:]]/
- Non-blank character (excludes spaces, control characters, and similar)
/[[:lower:]]/
- Lowercase alphabetical character
/[[:print:]]/
- Like [:graph:], but includes the space character
/[[:punct:]]/
- Punctuation character
/[[:space:]]/
- Whitespace character ([:blank:]
, newline, carriage return, etc.)
/[[:upper:]]/
- Uppercase alphabetical
/[[:xdigit:]]/
- Digit allowed in a hexadecimal number (i.e., 0-9a-fA-F)
Ruby also supports the following non-POSIX character classes:
/[[:word:]]/
- A character in one of the following Unicode general categories Letter, Mark, Number, Connector_Punctuation
/[[:ascii:]]/
- A character in the ASCII character set
# U+06F2 is "EXTENDED ARABIC-INDIC DIGIT TWO" /[[:digit:]]/.match("\u06F2") #=> #<MatchData "\u{06F2}"> /[[:upper:]][[:lower:]]/.match("Hello") #=> #<MatchData "He"> /[[:xdigit:]][[:xdigit:]]/.match("A6") #=> #<MatchData "A6">
The constructs described so far match a single character. They can be followed by a repetition metacharacter to specify how many times they need to occur. Such metacharacters are called quantifiers.
*
- Zero or more times
+
- One or more times
?
- Zero or one times (optional)
{
n}
- Exactly n times
{
n,}
- n or more times
{,
m}
- m or less times
{
n,
m}
- At least n and at most m times
At least one uppercase character (‘H’), at least one lowercase character (‘e’), two ‘l’ characters, then one ‘o’:
"Hello".match(/[[:upper:]]+[[:lower:]]+l{2}o/) #=> #<MatchData "Hello">
Repetition is greedy by default: as many occurrences as possible are matched while still allowing the overall match to succeed. By contrast, lazy matching makes the minimal amount of matches necessary for overall success. Most greedy metacharacters can be made lazy by following them with ?
. For the {n}
pattern, because it specifies an exact number of characters to match and not a variable number of characters, the ?
metacharacter instead makes the repeated pattern optional.
Both patterns below match the string. The first uses a greedy quantifier so ‘.+’ matches ‘<a><b>’; the second uses a lazy quantifier so ‘.+?’ matches ‘<a>’:
/<.+>/.match("<a><b>") #=> #<MatchData "<a><b>"> /<.+?>/.match("<a><b>") #=> #<MatchData "<a>">
A quantifier followed by +
matches possessively: once it has matched it does not backtrack. They behave like greedy quantifiers, but having matched they refuse to “give up” their match even if this jeopardises the overall match.
/<.*><.+>/.match("<a><b>") #=> #<MatchData "<a><b>"> /<.*+><.+>/.match("<a><b>") #=> nil /<.*><.++>/.match("<a><b>") #=> nil
Parentheses can be used for capturing. The text enclosed by the nth group of parentheses can be subsequently referred to with n. Within a pattern use the backreference \n
(e.g. \1
); outside of the pattern use MatchData[n]
(e.g. MatchData[1]
).
In this example, 'at'
is captured by the first group of parentheses, then referred to later with \1
:
/[csh](..) [csh]\1 in/.match("The cat sat in the hat") #=> #<MatchData "cat sat in" 1:"at">
Regexp#match
returns a MatchData
object which makes the captured text available with its [] method:
/[csh](..) [csh]\1 in/.match("The cat sat in the hat")[1] #=> 'at'
While Ruby supports an arbitrary number of numbered captured groups, only groups 1-9 are supported using the \n
backreference syntax.
Ruby also supports \0
as a special backreference, which references the entire matched string. This is also available at MatchData[0]
. Note that the \0
backreference cannot be used inside the regexp, as backreferences can only be used after the end of the capture group, and the \0
backreference uses the implicit capture group of the entire match. However, you can use this backreference when doing substitution:
"The cat sat in the hat".gsub(/[csh]at/, '\0s') # => "The cats sats in the hats"
Capture groups can be referred to by name when defined with the (?<
name>)
or (?'
name')
constructs.
/\$(?<dollars>\d+)\.(?<cents>\d+)/.match("$3.67") #=> #<MatchData "$3.67" dollars:"3" cents:"67"> /\$(?<dollars>\d+)\.(?<cents>\d+)/.match("$3.67")[:dollars] #=> "3"
Named groups can be backreferenced with \k<
name>
, where name is the group name.
/(?<vowel>[aeiou]).\k<vowel>.\k<vowel>/.match('ototomy') #=> #<MatchData "ototo" vowel:"o">
Note: A regexp can’t use named backreferences and numbered backreferences simultaneously. Also, if a named capture is used in a regexp, then parentheses used for grouping which would otherwise result in a unnamed capture are treated as non-capturing.
/(\w)(\w)/.match("ab").captures # => ["a", "b"] /(\w)(\w)/.match("ab").named_captures # => {} /(?<c>\w)(\w)/.match("ab").captures # => ["a"] /(?<c>\w)(\w)/.match("ab").named_captures # => {"c"=>"a"}
When named capture groups are used with a literal regexp on the left-hand side of an expression and the =~
operator, the captured text is also assigned to local variables with corresponding names.
/\$(?<dollars>\d+)\.(?<cents>\d+)/ =~ "$3.67" #=> 0 dollars #=> "3"
Parentheses also group the terms they enclose, allowing them to be quantified as one atomic whole.
The pattern below matches a vowel followed by 2 word characters:
/[aeiou]\w{2}/.match("Caenorhabditis elegans") #=> #<MatchData "aen">
Whereas the following pattern matches a vowel followed by a word character, twice, i.e. [aeiou]\w[aeiou]\w
: ‘enor’.
/([aeiou]\w){2}/.match("Caenorhabditis elegans") #=> #<MatchData "enor" 1:"or">
The (?:
…)
construct provides grouping without capturing. That is, it combines the terms it contains into an atomic whole without creating a backreference. This benefits performance at the slight expense of readability.
The first group of parentheses captures ‘n’ and the second ‘ti’. The second group is referred to later with the backreference \2
:
/I(n)ves(ti)ga\2ons/.match("Investigations") #=> #<MatchData "Investigations" 1:"n" 2:"ti">
The first group of parentheses is now made non-capturing with ‘?:’, so it still matches ‘n’, but doesn’t create the backreference. Thus, the backreference \1
now refers to ‘ti’.
/I(?:n)ves(ti)ga\1ons/.match("Investigations") #=> #<MatchData "Investigations" 1:"ti">
Grouping can be made atomic with (?>
pat)
. This causes the subexpression pat to be matched independently of the rest of the expression such that what it matches becomes fixed for the remainder of the match, unless the entire subexpression must be abandoned and subsequently revisited. In this way pat is treated as a non-divisible whole. Atomic grouping is typically used to optimise patterns so as to prevent the regular expression engine from backtracking needlessly.
The "
in the pattern below matches the first character of the string, then .*
matches Quote“. This causes the overall match to fail, so the text matched by .*
is backtracked by one position, which leaves the final character of the string available to match "
/".*"/.match('"Quote"') #=> #<MatchData "\"Quote\"">
If .*
is grouped atomically, it refuses to backtrack Quote“, even though this means that the overall match fails
/"(?>.*)"/.match('"Quote"') #=> nil
The \g<
name>
syntax matches the previous subexpression named name, which can be a group name or number, again. This differs from backreferences in that it re-executes the group rather than simply trying to re-match the same text.
This pattern matches a ( character and assigns it to the paren
group, tries to call that the paren
sub-expression again but fails, then matches a literal ):
/\A(?<paren>\(\g<paren>*\))*\z/ =~ '()' /\A(?<paren>\(\g<paren>*\))*\z/ =~ '(())' #=> 0 # ^1 # ^2 # ^3 # ^4 # ^5 # ^6 # ^7 # ^8 # ^9 # ^10
Matches at the beginning of the string, i.e. before the first character.
Enters a named capture group called paren
Matches a literal (, 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 a literal (, the second character in the string
Try to call paren
a third time, but fail because doing so would prevent an overall successful match
Match a literal ), the third character in the string. Marks the end of the second recursive call
Match a literal ), the fourth character in the string
Match the end of the string
The vertical bar metacharacter (|
) combines several expressions into a single one that matches any of the expressions. Each expression is an alternative.
/\w(and|or)\w/.match("Feliformia") #=> #<MatchData "form" 1:"or"> /\w(and|or)\w/.match("furandi") #=> #<MatchData "randi" 1:"and"> /\w(and|or)\w/.match("dissemblance") #=> nil
The \p{}
construct matches characters with the named property, much like POSIX bracket classes.
/\p{Alnum}/
- Alphabetic and numeric character
/\p{Alpha}/
- Alphabetic character
/\p{Blank}/
- Space or tab
/\p{Cntrl}/
- Control character
/\p{Digit}/
- Digit
/\p{Emoji}/
- Unicode emoji
/\p{Graph}/
- Non-blank character (excludes spaces, control 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)
/\p{Word}/
- A member of one of the following Unicode general category Letter, Mark, Number, Connector_Punctuation
/\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’s General Category value can also be matched with \p{
Ab}
where Ab is the category’s abbreviation as described below:
/\p{L}/
- ‘Letter’
/\p{Ll}/
- ‘Letter: Lowercase’
/\p{Lm}/
- ‘Letter: Mark’
/\p{Lo}/
- ‘Letter: Other’
/\p{Lt}/
- ‘Letter: Titlecase’
/\p{Lu}/
- ‘Letter: Uppercase
/\p{Lo}/
- ‘Letter: Other’
/\p{M}/
- ‘Mark’
/\p{Mn}/
- ‘Mark: Nonspacing’
/\p{Mc}/
- ‘Mark: Spacing Combining’
/\p{Me}/
- ‘Mark: Enclosing’
/\p{N}/
- ‘Number’
/\p{Nd}/
- ‘Number: Decimal Digit’
/\p{Nl}/
- ‘Number: Letter’
/\p{No}/
- ‘Number: Other’
/\p{P}/
- ‘Punctuation’
/\p{Pc}/
- ‘Punctuation: Connector’
/\p{Pd}/
- ‘Punctuation: Dash’
/\p{Ps}/
- ‘Punctuation: Open’
/\p{Pe}/
- ‘Punctuation: Close’
/\p{Pi}/
- ‘Punctuation: Initial Quote’
/\p{Pf}/
- ‘Punctuation: Final Quote’
/\p{Po}/
- ‘Punctuation: Other’
/\p{S}/
- ‘Symbol’
/\p{Sm}/
- ‘Symbol: Math’
/\p{Sc}/
- ‘Symbol: Currency’
/\p{Sc}/
- ‘Symbol: Currency’
/\p{Sk}/
- ‘Symbol: Modifier’
/\p{So}/
- ‘Symbol: Other’
/\p{Z}/
- ‘Separator’
/\p{Zs}/
- ‘Separator: Space’
/\p{Zl}/
- ‘Separator: Line’
/\p{Zp}/
- ‘Separator: Paragraph’
/\p{C}/
- ‘Other’
/\p{Cc}/
- ‘Other: Control’
/\p{Cf}/
- ‘Other: Format’
/\p{Cn}/
- ‘Other: Not Assigned’
/\p{Co}/
- ‘Other: Private Use’
/\p{Cs}/
- ‘Other: Surrogate’
Lastly, \p{}
matches a character’s Unicode script. The following scripts are supported: Arabic, Armenian, Balinese, Bengali, Bopomofo, Braille, Buginese, Buhid, Canadian_Aboriginal, Carian, Cham, Cherokee, Common, Coptic, Cuneiform, Cypriot, Cyrillic, Deseret, Devanagari, Ethiopic, Georgian, Glagolitic, Gothic, Greek, Gujarati, Gurmukhi, Han, Hangul, Hanunoo, Hebrew, Hiragana, Inherited, Kannada, Katakana, Kayah_Li, Kharoshthi, Khmer, Lao, Latin, Lepcha, Limbu, Linear_B, Lycian, Lydian, Malayalam, Mongolian, Myanmar, New_Tai_Lue, Nko, Ogham, Ol_Chiki, Old_Italic, Old_Persian, Oriya, Osmanya, Phags_Pa, Phoenician, Rejang, Runic, Saurashtra, Shavian, Sinhala, Sundanese, Syloti_Nagri, Syriac, Tagalog, Tagbanwa, Tai_Le, Tamil, Telugu, Thaana, Thai, Tibetan, Tifinagh, Ugaritic, Vai, and Yi.
Unicode codepoint U+06E9 is named “ARABIC PLACE OF SAJDAH” and belongs to the Arabic script:
/\p{Arabic}/.match("\u06E9") #=> #<MatchData "\u06E9">
All character properties can be inverted by prefixing their name with a caret (^
).
Letter ‘A’ is not in the Unicode Ll (Letter; Lowercase) category, so this match succeeds:
/\p{^Ll}/.match("A") #=> #<MatchData "A">
Anchors are metacharacter that match the zero-width positions between characters, anchoring the match to a specific position.
^
- Matches beginning of line
$
- Matches end of line
\A
- Matches beginning of string.
\Z
- Matches end of string. If string ends with a newline, it matches just before newline
\z
- Matches end of string
\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
\b
- Matches word boundaries when outside brackets; backspace (0x08) when inside brackets
\B
- Matches non-word boundaries
(?=
pat)
- Positive lookahead assertion: ensures that the following characters match pat, but doesn’t include those characters in the matched text
(?!
pat)
- Negative lookahead assertion: ensures that the following characters do not match pat, but doesn’t include those characters in the matched text
(?<=
pat)
- Positive lookbehind assertion: ensures that the preceding characters match pat, but doesn’t include those characters in the matched text
(?<!
pat)
- Negative lookbehind assertion: ensures that the preceding characters do not match pat, but doesn’t include those characters in the matched text
\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/ =~ "abc" #=> 0 /(?<=ab)c/ =~ "abc" #=> 2
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/
If a pattern isn’t anchored it can begin at any point in the string:
/real/.match("surrealist") #=> #<MatchData "real">
Anchoring the pattern to the beginning of the string forces the match to start there. ‘real’ doesn’t occur at the beginning of the string, so now the match fails:
/\Areal/.match("surrealist") #=> nil
The match below fails because although ‘Demand’ contains ‘and’, the pattern does not occur at a word boundary.
/\band/.match("Demand")
Whereas in the following example ‘and’ has been anchored to a non-word boundary so instead of matching the first ‘and’ it matches from the fourth letter of ‘demand’ instead:
/\Band.+/.match("Supply and demand curve") #=> #<MatchData "and curve">
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 favours the <b>bold</b>") #=> #<MatchData "bold">
The end delimiter for a regexp can be followed by one or more single-letter options which control how the pattern can match.
/pat/i
- Ignore case
/pat/m
- Treat a newline as a character matched by .
/pat/x
- Ignore whitespace and comments in the pattern
/pat/o
- Perform #{}
interpolation only once
i
, m
, and x
can also be applied on the subexpression level with the (?
on-
off)
construct, which enables options on, and disables options off for the expression enclosed by the parentheses:
/a(?i:b)c/.match('aBc') #=> #<MatchData "aBc"> /a(?-i:b)c/i.match('ABC') #=> nil
Additionally, these options can also be toggled for the remainder of the pattern:
/a(?i)bc/.match('abC') #=> #<MatchData "abC">
Options may also be used with Regexp.new
:
Regexp.new("abc", Regexp::IGNORECASE) #=> /abc/i Regexp.new("abc", Regexp::MULTILINE) #=> /abc/m Regexp.new("abc # Comment", Regexp::EXTENDED) #=> /abc # Comment/x Regexp.new("abc", Regexp::IGNORECASE | Regexp::MULTILINE) #=> /abc/mi Regexp.new("abc", "i") #=> /abc/i Regexp.new("abc", "m") #=> /abc/m Regexp.new("abc # Comment", "x") #=> /abc # Comment/x Regexp.new("abc", "im") #=> /abc/mi
As mentioned above, the x
option enables free-spacing mode. Literal white space inside the pattern is ignored, and the octothorpe (#
) character introduces a comment until the end of the line. This allows the components of the pattern to be organized in a potentially more readable fashion.
A contrived pattern to match a number with optional decimal places:
float_pat = /\A [[:digit:]]+ # 1 or more digits before the decimal point (\. # Decimal point [[:digit:]]+ # 1 or more digits after the decimal point )? # The decimal point and following digits are optional \Z/x float_pat.match('3.14') #=> #<MatchData "3.14" 1:".14">
There are a number of strategies for matching whitespace:
Use a pattern such as \s
or \p{Space}
.
Use escaped whitespace such as \
, i.e. a space preceded by a backslash.
Use a character class such as [ ]
.
Comments can be included in a non-x
pattern with the (?#
comment)
construct, where comment is arbitrary text ignored by the regexp engine.
Comments in regexp literals cannot include unescaped terminator characters.
Encoding
Regular expressions are assumed to use the source encoding. This can be overridden with one of the following modifiers.
/
pat/u
- UTF-8
/
pat/e
- EUC-JP
/
pat/s
- Windows-31J
/
pat/n
- ASCII-8BIT
A regexp can be matched against a string when they either share an encoding, or the regexp’s encoding is US-ASCII and the string’s encoding is ASCII-compatible.
If a match between incompatible encodings is attempted an Encoding::CompatibilityError
exception is raised.
The Regexp#fixed_encoding?
predicate indicates whether the regexp has a fixed encoding, that is one incompatible with ASCII. A regexp’s encoding can be explicitly fixed by supplying Regexp::FIXEDENCODING
as the second argument of Regexp.new
:
r = Regexp.new("a".force_encoding("iso-8859-1"),Regexp::FIXEDENCODING) r =~ "a\u3042" # raises Encoding::CompatibilityError: incompatible encoding regexp match # (ISO-8859-1 regexp with UTF-8 string)
Pattern matching sets some global variables :
$~
is equivalent to Regexp.last_match
;
$&
contains the complete matched text;
$`
contains string before match;
$'
contains string after match;
$1
, $2
and so on contain text matching first, second, etc capture group;
$+
contains last capture group.
Example:
m = /s(\w{2}).*(c)/.match('haystack') #=> #<MatchData "stac" 1:"ta" 2:"c"> $~ #=> #<MatchData "stac" 1:"ta" 2:"c"> Regexp.last_match #=> #<MatchData "stac" 1:"ta" 2:"c"> $& #=> "stac" # same as m[0] $` #=> "hay" # same as m.pre_match $' #=> "k" # same as m.post_match $1 #=> "ta" # same as m[1] $2 #=> "c" # same as m[2] $3 #=> nil # no third group in pattern $+ #=> "c" # same as m[-1]
These global variables are thread-local and method-local variables.
Certain pathological combinations of constructs can lead to abysmally bad performance.
Consider a string of 25 as, a d, 4 as, and a c.
s = 'a' * 25 + 'd' + 'a' * 4 + 'c' #=> "aaaaaaaaaaaaaaaaaaaaaaaaadaaaac"
The following patterns match instantly as you would expect:
/(b|a)/ =~ s #=> 0 /(b|a+)/ =~ s #=> 0 /(b|a+)*/ =~ s #=> 0
However, the following pattern takes appreciably longer:
/(b|a+)*c/ =~ s #=> 26
This happens because an atom in the regexp is quantified by both an immediate +
and an enclosing *
with nothing to differentiate which is in control of any particular character. The nondeterminism that results produces super-linear performance. (Consult Mastering Regular Expressions (3rd ed.), pp 222, by Jeffery Friedl, for an in-depth analysis). This particular case can be fixed by use of atomic grouping, which prevents the unnecessary backtracking:
(start = Time.now) && /(b|a+)*c/ =~ s && (Time.now - start) #=> 24.702736882 (start = Time.now) && /(?>b|a+)*c/ =~ s && (Time.now - start) #=> 0.000166571
A similar case is typified by the following example, which takes approximately 60 seconds to execute for me:
Match a string of 29 as against a pattern of 29 optional as followed by 29 mandatory as:
Regexp.new('a?' * 29 + 'a' * 29) =~ 'a' * 29
The 29 optional as match the string, but this prevents the 29 mandatory as that follow from matching. Ruby must then backtrack repeatedly so as to satisfy as many of the optional matches as it can while still matching the mandatory 29. It is plain to us that none of the optional matches can succeed, but this fact unfortunately eludes Ruby.
The best way to improve performance is to significantly reduce the amount of backtracking needed. For this case, instead of individually matching 29 optional as, a range of optional as can be matched all at once with a{0,29}:
Regexp.new('a{0,29}' + 'a' * 29) =~ 'a' * 29
Timeout
There are two APIs to set timeout. One is Regexp.timeout=
, which is process-global configuration of timeout for Regexp
matching.
Regexp.timeout = 3 s = 'a' * 25 + 'd' + 'a' * 4 + 'c' /(b|a+)*c/ =~ s #=> This raises an exception in three seconds
The other is timeout keyword of Regexp.new
.
re = Regexp.new("(b|a+)*c", timeout: 3) s = 'a' * 25 + 'd' + 'a' * 4 + 'c' /(b|a+)*c/ =~ s #=> This raises an exception in three seconds
When using Regexps to process untrusted input, you should use the timeout feature to avoid excessive backtracking. Otherwise, a malicious user can provide input to Regexp
causing Denial-of-Service attack. Note that the timeout is not set by default because an appropriate limit highly depends on an application requirement and context.
Ripper
is a Ruby script parser.
You can get information from the parser with event-based style. Information such as abstract syntax trees or simple lexical analysis of the Ruby program.
Ripper
provides an easy interface for parsing your program into a symbolic expression tree (or S-expression).
Understanding the output of the parser may come as a challenge, it’s recommended you use PP
to format the output for legibility.
require 'ripper' require 'pp' pp Ripper.sexp('def hello(world) "Hello, #{world}!"; end') #=> [:program, [[:def, [:@ident, "hello", [1, 4]], [:paren, [:params, [[:@ident, "world", [1, 10]]], nil, nil, nil, nil, nil, nil]], [:bodystmt, [[:string_literal, [:string_content, [:@tstring_content, "Hello, ", [1, 18]], [:string_embexpr, [[:var_ref, [:@ident, "world", [1, 27]]]]], [:@tstring_content, "!", [1, 33]]]]], nil, nil, nil]]]]
You can see in the example above, the expression starts with :program
.
From here, a method definition at :def
, followed by the method’s identifier :@ident
. After the method’s identifier comes the parentheses :paren
and the method parameters under :params
.
Next is the method body, starting at :bodystmt
(stmt
meaning statement), which contains the full definition of the method.
In our case, we’re simply returning a String
, so next we have the :string_literal
expression.
Within our :string_literal
you’ll notice two @tstring_content
, this is the literal part for Hello,
and !
. Between the two @tstring_content
statements is a :string_embexpr
, where embexpr is an embedded expression. Our expression consists of a local variable, or var_ref
, with the identifier (@ident
) of world
.
ruby 1.9 (support CVS HEAD only)
bison 1.28 or later (Other yaccs do not work)
Ruby License.
Minero Aoki
aamine@loveruby.net
SocketError
is the error class for socket.
StringScanner
provides for lexical scanning operations on a String
. Here is an example of its usage:
require 'strscan' s = StringScanner.new('This is an example string') s.eos? # -> false p s.scan(/\w+/) # -> "This" p s.scan(/\w+/) # -> nil p s.scan(/\s+/) # -> " " p s.scan(/\s+/) # -> nil p s.scan(/\w+/) # -> "is" s.eos? # -> false p s.scan(/\s+/) # -> " " p s.scan(/\w+/) # -> "an" p s.scan(/\s+/) # -> " " p s.scan(/\w+/) # -> "example" p s.scan(/\s+/) # -> " " p s.scan(/\w+/) # -> "string" s.eos? # -> true p s.scan(/\s+/) # -> nil p s.scan(/\w+/) # -> nil
Scanning a string means remembering the position of a scan pointer, which is just an index. The point of scanning is to move forward a bit at a time, so matches are sought after the scan pointer; usually immediately after it.
Given the string “test string”, here are the pertinent scan pointer positions:
t e s t s t r i n g 0 1 2 ... 1 0
When you scan
for a pattern (a regular expression), the match must occur at the character after the scan pointer. If you use scan_until
, then the match can occur anywhere after the scan pointer. In both cases, the scan pointer moves just beyond the last character of the match, ready to scan again from the next character onwards. This is demonstrated by the example above.
Method
Categories There are other methods besides the plain scanners. You can look ahead in the string without actually scanning. You can access the most recent match. You can modify the string being scanned, reset or terminate the scanner, find out or change the position of the scan pointer, skip ahead, and so on.
beginning_of_line?
(#bol?
)
Data
There are aliases to several of the methods.