Returns true if path
matches against pattern
. The pattern is not a regular expression; instead it follows rules similar to shell filename globbing. It may contain the following metacharacters:
*
Matches any file. Can be restricted by other values in the glob. Equivalent to /.*/x
in regexp.
*
Matches all regular files
c*
Matches all files beginning with c
*c
Matches all files ending with c
*c*
Matches all files that have c
in them (including at the beginning or end).
To match hidden files (that start with a .
) set the File::FNM_DOTMATCH flag.
**
Matches directories recursively or files expansively.
?
Matches any one character. Equivalent to /.{1}/
in regexp.
[set]
Matches any one character in set
. Behaves exactly like character sets in Regexp
, including set negation ([^a-z]
).
\
Escapes the next metacharacter.
{a,b}
Matches pattern a and pattern b if File::FNM_EXTGLOB flag is enabled. Behaves like a Regexp
union ((?:a|b)
).
flags
is a bitwise OR of the FNM_XXX
constants. The same glob pattern and flags are used by Dir::glob
.
Examples:
File.fnmatch('cat', 'cat') #=> true # match entire string File.fnmatch('cat', 'category') #=> false # only match partial string File.fnmatch('c{at,ub}s', 'cats') #=> false # { } isn't supported by default File.fnmatch('c{at,ub}s', 'cats', File::FNM_EXTGLOB) #=> true # { } is supported on FNM_EXTGLOB File.fnmatch('c?t', 'cat') #=> true # '?' match only 1 character File.fnmatch('c??t', 'cat') #=> false # ditto File.fnmatch('c*', 'cats') #=> true # '*' match 0 or more characters File.fnmatch('c*t', 'c/a/b/t') #=> true # ditto File.fnmatch('ca[a-z]', 'cat') #=> true # inclusive bracket expression File.fnmatch('ca[^t]', 'cat') #=> false # exclusive bracket expression ('^' or '!') File.fnmatch('cat', 'CAT') #=> false # case sensitive File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true # case insensitive File.fnmatch('cat', 'CAT', File::FNM_SYSCASE) #=> true or false # depends on the system default File.fnmatch('?', '/', File::FNM_PATHNAME) #=> false # wildcard doesn't match '/' on FNM_PATHNAME File.fnmatch('*', '/', File::FNM_PATHNAME) #=> false # ditto File.fnmatch('[/]', '/', File::FNM_PATHNAME) #=> false # ditto File.fnmatch('\?', '?') #=> true # escaped wildcard becomes ordinary File.fnmatch('\a', 'a') #=> true # escaped ordinary remains ordinary File.fnmatch('\a', '\a', File::FNM_NOESCAPE) #=> true # FNM_NOESCAPE makes '\' ordinary File.fnmatch('[\?]', '?') #=> true # can escape inside bracket expression File.fnmatch('*', '.profile') #=> false # wildcard doesn't match leading File.fnmatch('*', '.profile', File::FNM_DOTMATCH) #=> true # period by default. File.fnmatch('.*', '.profile') #=> true File.fnmatch('**/*.rb', 'main.rb') #=> false File.fnmatch('**/*.rb', './main.rb') #=> false File.fnmatch('**/*.rb', 'lib/song.rb') #=> true File.fnmatch('**.rb', 'main.rb') #=> true File.fnmatch('**.rb', './main.rb') #=> false File.fnmatch('**.rb', 'lib/song.rb') #=> true File.fnmatch('*', 'dave/.profile') #=> true File.fnmatch('**/foo', 'a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch('**/foo', '/a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch('**/foo', 'c:/a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch('**/foo', 'a/.b/c/foo', File::FNM_PATHNAME) #=> false File.fnmatch('**/foo', 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
MatchData
encapsulates the result of matching a Regexp
against string. It is returned by Regexp#match
and String#match
, and also stored in a global variable returned by Regexp.last_match
.
Usage:
url = 'https://docs.ruby-lang.org/en/2.5.0/MatchData.html' m = url.match(/(\d\.?)+/) # => #<MatchData "2.5.0" 1:"0"> m.string # => "https://docs.ruby-lang.org/en/2.5.0/MatchData.html" m.regexp # => /(\d\.?)+/ # entire matched substring: m[0] # => "2.5.0" # Working with unnamed captures m = url.match(%r{([^/]+)/([^/]+)\.html$}) m.captures # => ["2.5.0", "MatchData"] m[1] # => "2.5.0" m.values_at(1, 2) # => ["2.5.0", "MatchData"] # Working with named captures m = url.match(%r{(?<version>[^/]+)/(?<module>[^/]+)\.html$}) m.captures # => ["2.5.0", "MatchData"] m.named_captures # => {"version"=>"2.5.0", "module"=>"MatchData"} m[:version] # => "2.5.0" m.values_at(:version, :module) # => ["2.5.0", "MatchData"] # Numerical indexes are working, too m[1] # => "2.5.0" m.values_at(1, 2) # => ["2.5.0", "MatchData"]
Parts of last MatchData
(returned by Regexp.last_match
) are also aliased as global variables:
$~
is Regexp.last_match
;
$&
is Regexp.last_match
[ 0 ]
;
$1
, $2
, and so on are Regexp.last_match
[ i ]
(captures by number);
$`
is Regexp.last_match
.pre_match
;
$'
is Regexp.last_match
.post_match
;
$+
is Regexp.last_match
[ -1 ]
(the last capture).
See also “Special global variables” section in Regexp
documentation.
Raised when attempting to convert special float values (in particular Infinity
or NaN
) to numerical classes which don’t support them.
Float::INFINITY.to_r #=> FloatDomainError: Infinity
The Benchmark
module provides methods to measure and report the time used to execute Ruby code.
Measure the time to construct the string given by the expression "a"*1_000_000_000
:
require 'benchmark' puts Benchmark.measure { "a"*1_000_000_000 }
On my machine (OSX 10.8.3 on i5 1.7 GHz) this generates:
0.350000 0.400000 0.750000 ( 0.835234)
This report shows the user CPU time, system CPU time, the sum of the user and system CPU times, and the elapsed real time. The unit of time is seconds.
Do some experiments sequentially using the bm
method:
require 'benchmark' n = 5000000 Benchmark.bm do |x| x.report { for i in 1..n; a = "1"; end } x.report { n.times do ; a = "1"; end } x.report { 1.upto(n) do ; a = "1"; end } end
The result:
user system total real 1.010000 0.000000 1.010000 ( 1.014479) 1.000000 0.000000 1.000000 ( 0.998261) 0.980000 0.000000 0.980000 ( 0.981335)
Continuing the previous example, put a label in each report:
require 'benchmark' n = 5000000 Benchmark.bm(7) do |x| x.report("for:") { for i in 1..n; a = "1"; end } x.report("times:") { n.times do ; a = "1"; end } x.report("upto:") { 1.upto(n) do ; a = "1"; end } end
The result:
user system total real for: 1.010000 0.000000 1.010000 ( 1.015688) times: 1.000000 0.000000 1.000000 ( 1.003611) upto: 1.030000 0.000000 1.030000 ( 1.028098)
The times for some benchmarks depend on the order in which items are run. These differences are due to the cost of memory allocation and garbage collection. To avoid these discrepancies, the bmbm
method is provided. For example, to compare ways to sort an array of floats:
require 'benchmark' array = (1..1000000).map { rand } Benchmark.bmbm do |x| x.report("sort!") { array.dup.sort! } x.report("sort") { array.dup.sort } end
The result:
Rehearsal ----------------------------------------- sort! 1.490000 0.010000 1.500000 ( 1.490520) sort 1.460000 0.000000 1.460000 ( 1.463025) -------------------------------- total: 2.960000sec user system total real sort! 1.460000 0.000000 1.460000 ( 1.460465) sort 1.450000 0.010000 1.460000 ( 1.448327)
Report statistics of sequential experiments with unique labels, using the benchmark
method:
require 'benchmark' include Benchmark # we need the CAPTION and FORMAT constants n = 5000000 Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| tf = x.report("for:") { for i in 1..n; a = "1"; end } tt = x.report("times:") { n.times do ; a = "1"; end } tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } [tf+tt+tu, (tf+tt+tu)/3] end
The result:
user system total real for: 0.950000 0.000000 0.950000 ( 0.952039) times: 0.980000 0.000000 0.980000 ( 0.984938) upto: 0.950000 0.000000 0.950000 ( 0.946787) >total: 2.880000 0.000000 2.880000 ( 2.883764) >avg: 0.960000 0.000000 0.960000 ( 0.961255)
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.
Module Math provides methods for basic trigonometric, logarithmic, and transcendental functions, and for extracting roots.
You can write its constants and method calls thus:
Math::PI # => 3.141592653589793 Math::E # => 2.718281828459045 Math.sin(0.0) # => 0.0 Math.cos(0.0) # => 1.0
If you include module Math, you can write simpler forms:
include Math PI # => 3.141592653589793 E # => 2.718281828459045 sin(0.0) # => 0.0 cos(0.0) # => 1.0
For simplicity, the examples here assume:
include Math INFINITY = Float::INFINITY
The domains and ranges for the methods are denoted by open or closed intervals, using, respectively, parentheses or square brackets:
An open interval does not include the endpoints:
(-INFINITY, INFINITY)
A closed interval includes the endpoints:
[-1.0, 1.0]
A half-open interval includes one endpoint, but not the other:
[1.0, INFINITY)
Many values returned by Math methods are numerical approximations. This is because many such values are, in mathematics, of infinite precision, while in numerical computation the precision is finite.
Thus, in mathematics, cos(π/2) is exactly zero, but in our computation cos(PI/2)
is a number very close to zero:
cos(PI/2) # => 6.123031769111886e-17
For very large and very small returned values, we have added formatted numbers for clarity:
tan(PI/2) # => 1.633123935319537e+16 # 16331239353195370.0 tan(PI) # => -1.2246467991473532e-16 # -0.0000000000000001
See class Float
for the constants that affect Ruby’s floating-point arithmetic.
::cos
: Returns the cosine of the given argument.
::sin
: Returns the sine of the given argument.
::tan
: Returns the tangent of the given argument.
::acos
: Returns the arc cosine of the given argument.
::asin
: Returns the arc sine of the given argument.
::atan
: Returns the arc tangent of the given argument.
::atan2
: Returns the arg tangent of two given arguments.
::cosh
: Returns the hyperbolic cosine of the given argument.
::sinh
: Returns the hyperbolic sine of the given argument.
::tanh
: Returns the hyperbolic tangent of the given argument.
::acosh
: Returns the inverse hyperbolic cosine of the given argument.
::asinh
: Returns the inverse hyperbolic sine of the given argument.
::atanh
: Returns the inverse hyperbolic tangent of the given argument.
::exp
: Returns the value of a given value raised to a given power.
::log
: Returns the logarithm of a given value in a given base.
::log10
: Returns the base 10 logarithm of the given argument.
::log2
: Returns the base 2 logarithm of the given argument.
::frexp
: Returns the fraction and exponent of the given argument.
::ldexp
: Returns the value for a given fraction and exponent.
::cbrt
: Returns the cube root of the given argument.
::sqrt
: Returns the square root of the given argument.
::erf
: Returns the value of the Gauss error function for the given argument.
::erfc
: Returns the value of the complementary error function for the given argument.
::gamma
: Returns the value of the gamma function for the given argument.
::lgamma
: Returns the value of the logarithmic gamma function for the given argument.
::hypot
: Returns sqrt(a**2 + b**2)
for the given a
and b
.
Represents a regular expression literal that contains interpolation that is being used in the predicate of a conditional to implicitly match against the last line read by an IO
object.
if /foo #{bar} baz/ then end ^^^^^^^^^^^^^^^^
Generated when trying to lookup a gem to indicate that the gem was found, but that it isn’t usable on the current platform.
fetch and install read these and report them to the user to aid in figuring out why a gem couldn’t be installed.
Raised when a gem dependencies file specifies a ruby version that does not match the current version.
Represents the use of a case statement for pattern matching.
case true in false end ^^^^^^^^^
Represents a regular expression literal used in the predicate of a conditional to implicitly match against the last line read by an IO
object.
if /foo/i then end ^^^^^^
Represents writing local variables using a regular expression match with named capture groups.
/(?<foo>bar)/ =~ baz ^^^^^^^^^^^^^^^^^^^^
Response class for Non-Authoritative Information
responses (status code 203).
The Non-Authoritative Information
response indicates that the server is a transforming proxy (such as a Web accelerator) that received a 200 OK response from its origin, and is returning a modified version of the origin’s response.
References:
The dispatcher class fires events for nodes that are found while walking an AST to all registered listeners. It’s useful for performing different types of analysis on the AST while only having to walk the tree once.
To use the dispatcher, you would first instantiate it and register listeners for the events you’re interested in:
class OctalListener def on_integer_node_enter(node) if node.octal? && !node.slice.start_with?("0o") warn("Octal integers should be written with the 0o prefix") end end end dispatcher = Dispatcher.new dispatcher.register(listener, :on_integer_node_enter)
Then, you can walk any number of trees and dispatch events to the listeners:
result = Prism.parse("001 + 002 + 003") dispatcher.dispatch(result.value)
Optionally, you can also use ‘#dispatch_once` to dispatch enter and leave events for a single node without recursing further down the tree. This can be useful in circumstances where you want to reuse the listeners you already have registers but want to stop walking the tree at a certain point.
integer = result.value.statements.body.first.receiver.receiver dispatcher.dispatch_once(integer)
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 and class Object.
Includes module Comparable.
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.
Continuation
objects are generated by Kernel#callcc
, after having +require+d continuation. They hold a return address and execution context, allowing a nonlocal return to the end of the callcc
block from anywhere within a program. Continuations are somewhat analogous to a structured version of C’s setjmp/longjmp
(although they contain more state, so you might consider them closer to threads).
For instance:
require "continuation" arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ] callcc{|cc| $cc = cc} puts(message = arr.shift) $cc.call unless message =~ /Max/
produces:
Freddie Herbie Ron Max
Also you can call callcc in other methods:
require "continuation" def g arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ] cc = callcc { |cc| cc } puts arr.shift return cc, arr.size end def f c, size = g c.call(c) if size > 1 end f
This (somewhat contrived) example allows the inner loop to abandon processing early:
require "continuation" callcc {|cont| for i in 0..4 print "#{i}: " for j in i*5...(i+1)*5 cont.call() if j == 17 printf "%3d", j end end } puts
produces:
0: 0 1 2 3 4 1: 5 6 7 8 9 2: 10 11 12 13 14 3: 15 16
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"]
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
internally).
These methods do not affect other internal enumeration methods, unless the underlying iteration method itself has side-effect, e.g. IO#each_line
.
FrozenError
will be raised if these methods are called against a frozen enumerator. Since rewind
and feed
also change state for external iteration, these methods may raise FrozenError
too.
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)
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!
Class Date provides methods for storing and manipulating calendar dates.
Consider using class Time instead of class Date if:
You need both dates and times; Date handles only dates.
You need only Gregorian dates (and not Julian dates); see Julian and Gregorian Calendars.
A Date object, once created, is immutable, and cannot be modified.
You can create a date for the current date, using Date.today
:
Date.today # => #<Date: 1999-12-31>
You can create a specific date from various combinations of arguments:
Date.new
takes integer year, month, and day-of-month:
Date.new(1999, 12, 31) # => #<Date: 1999-12-31>
Date.ordinal
takes integer year and day-of-year:
Date.ordinal(1999, 365) # => #<Date: 1999-12-31>
Date.jd
takes integer Julian day:
Date.jd(2451544) # => #<Date: 1999-12-31>
Date.commercial
takes integer commercial data (year, week, day-of-week):
Date.commercial(1999, 52, 5) # => #<Date: 1999-12-31>
Date.parse
takes a string, which it parses heuristically:
Date.parse('1999-12-31') # => #<Date: 1999-12-31> Date.parse('31-12-1999') # => #<Date: 1999-12-31> Date.parse('1999-365') # => #<Date: 1999-12-31> Date.parse('1999-W52-5') # => #<Date: 1999-12-31>
Date.strptime
takes a date string and a format string, then parses the date string according to the format string:
Date.strptime('1999-12-31', '%Y-%m-%d') # => #<Date: 1999-12-31> Date.strptime('31-12-1999', '%d-%m-%Y') # => #<Date: 1999-12-31> Date.strptime('1999-365', '%Y-%j') # => #<Date: 1999-12-31> Date.strptime('1999-W52-5', '%G-W%V-%u') # => #<Date: 1999-12-31> Date.strptime('1999 52 5', '%Y %U %w') # => #<Date: 1999-12-31> Date.strptime('1999 52 5', '%Y %W %u') # => #<Date: 1999-12-31> Date.strptime('fri31dec99', '%a%d%b%y') # => #<Date: 1999-12-31>
See also the specialized methods in “Specialized Format Strings” in Formats for Dates and Times
limit
Certain singleton methods in Date that parse string arguments also take optional keyword argument limit
, which can limit the length of the string argument.
When limit
is:
Non-negative: raises ArgumentError
if the string length is greater than limit.
Other numeric or nil
: ignores limit
.
Other non-numeric: raises TypeError
.