Iterates over the entries (files and subdirectories) in the directory, yielding a Pathname
object for each entry.
Converts a SyntaxError
message to a path
Handles the case where the filename has a colon in it such as on a windows file system: github.com/ruby/syntax_suggest/issues/111
Example:
message = "/tmp/scratch:2:in `require_relative': /private/tmp/bad.rb:1: syntax error, unexpected `end' (SyntaxError)" puts PathnameFromMessage.new(message).call.name # => "/tmp/scratch.rb"
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
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 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 an instance of String
A rational number can be represented as a pair of integer numbers: a/b (b>0), where a is the numerator and b is the denominator. Integer
a equals rational a/1 mathematically.
You can create a Rational object explicitly with:
A rational literal.
You can convert certain objects to Rationals with:
Method Rational
.
Examples
Rational(1) #=> (1/1) Rational(2, 3) #=> (2/3) Rational(4, -6) #=> (-2/3) # Reduced. 3.to_r #=> (3/1) 2/3r #=> (2/3)
You can also create rational objects from floating-point numbers or strings.
Rational(0.3) #=> (5404319552844595/18014398509481984) Rational('0.3') #=> (3/10) Rational('2/3') #=> (2/3) 0.3.to_r #=> (5404319552844595/18014398509481984) '0.3'.to_r #=> (3/10) '2/3'.to_r #=> (2/3) 0.3.rationalize #=> (3/10)
A rational object is an exact number, which helps you to write programs without any rounding errors.
10.times.inject(0) {|t| t + 0.1 } #=> 0.9999999999999999 10.times.inject(0) {|t| t + Rational('0.1') } #=> (1/1)
However, when an expression includes an inexact component (numerical value or operation), it will produce an inexact result.
Rational(10) / 3 #=> (10/3) Rational(10) / 3.0 #=> 3.3333333333333335 Rational(-8) ** Rational(1, 3) #=> (1.0000000000000002+1.7320508075688772i)
DateTime
A subclass of Date
that easily handles date, hour, minute, second, and offset.
DateTime
class is considered deprecated. Use Time
class.
DateTime
does not consider any leap seconds, does not track any summer time rules.
A DateTime
object is created with DateTime::new
, DateTime::jd
, DateTime::ordinal
, DateTime::commercial
, DateTime::parse
, DateTime::strptime
, DateTime::now
, Time#to_datetime
, etc.
require 'date' DateTime.new(2001,2,3,4,5,6) #=> #<DateTime: 2001-02-03T04:05:06+00:00 ...>
The last element of day, hour, minute, or second can be a fractional number. The fractional number’s precision is assumed at most nanosecond.
DateTime.new(2001,2,3.5) #=> #<DateTime: 2001-02-03T12:00:00+00:00 ...>
An optional argument, the offset, indicates the difference between the local time and UTC. For example, Rational(3,24)
represents ahead of 3 hours of UTC, Rational(-5,24)
represents behind of 5 hours of UTC. The offset should be -1 to +1, and its precision is assumed at most second. The default value is zero (equals to UTC).
DateTime.new(2001,2,3,4,5,6,Rational(3,24)) #=> #<DateTime: 2001-02-03T04:05:06+03:00 ...>
The offset also accepts string form:
DateTime.new(2001,2,3,4,5,6,'+03:00') #=> #<DateTime: 2001-02-03T04:05:06+03:00 ...>
An optional argument, the day of calendar reform (start
), denotes a Julian day number, which should be 2298874 to 2426355 or negative/positive infinity. The default value is Date::ITALY
(2299161=1582-10-15).
A DateTime
object has various methods. See each reference.
d = DateTime.parse('3rd Feb 2001 04:05:06+03:30') #=> #<DateTime: 2001-02-03T04:05:06+03:30 ...> d.hour #=> 4 d.min #=> 5 d.sec #=> 6 d.offset #=> (7/48) d.zone #=> "+03:30" d += Rational('1.5') #=> #<DateTime: 2001-02-04%16:05:06+03:30 ...> d = d.new_offset('+09:00') #=> #<DateTime: 2001-02-04%21:35:06+09:00 ...> d.strftime('%I:%M:%S %p') #=> "09:35:06 PM" d > DateTime.new(1999) #=> true
DateTime
and when should you use Time
? It’s a common misconception that William Shakespeare and Miguel de Cervantes died on the same day in history - so much so that UNESCO named April 23 as World Book Day because of this fact. However, because England hadn’t yet adopted the Gregorian Calendar Reform (and wouldn’t until 1752) their deaths are actually 10 days apart. Since Ruby’s Time
class implements a proleptic Gregorian calendar and has no concept of calendar reform there’s no way to express this with Time
objects. This is where DateTime
steps in:
shakespeare = DateTime.iso8601('1616-04-23', Date::ENGLAND) #=> Tue, 23 Apr 1616 00:00:00 +0000 cervantes = DateTime.iso8601('1616-04-23', Date::ITALY) #=> Sat, 23 Apr 1616 00:00:00 +0000
Already you can see something is weird - the days of the week are different. Taking this further:
cervantes == shakespeare #=> false (shakespeare - cervantes).to_i #=> 10
This shows that in fact they died 10 days apart (in reality 11 days since Cervantes died a day earlier but was buried on the 23rd). We can see the actual date of Shakespeare’s death by using the gregorian
method to convert it:
shakespeare.gregorian #=> Tue, 03 May 1616 00:00:00 +0000
So there’s an argument that all the celebrations that take place on the 23rd April in Stratford-upon-Avon are actually the wrong date since England is now using the Gregorian calendar. You can see why when we transition across the reform date boundary:
# start off with the anniversary of Shakespeare's birth in 1751 shakespeare = DateTime.iso8601('1751-04-23', Date::ENGLAND) #=> Tue, 23 Apr 1751 00:00:00 +0000 # add 366 days since 1752 is a leap year and April 23 is after February 29 shakespeare + 366 #=> Thu, 23 Apr 1752 00:00:00 +0000 # add another 365 days to take us to the anniversary in 1753 shakespeare + 366 + 365 #=> Fri, 04 May 1753 00:00:00 +0000
As you can see, if we’re accurately tracking the number of solar years since Shakespeare’s birthday then the correct anniversary date would be the 4th May and not the 23rd April.
So when should you use DateTime
in Ruby and when should you use Time
? Almost certainly you’ll want to use Time
since your app is probably dealing with current dates and times. However, if you need to deal with dates and times in a historical context you’ll want to use DateTime
to avoid making the same mistakes as UNESCO. If you also have to deal with timezones then best of luck - just bear in mind that you’ll probably be dealing with local solar times, since it wasn’t until the 19th century that the introduction of the railways necessitated the need for Standard Time and eventually timezones.
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.
Method
objects are created by Object#method
, and are associated with a particular object (not just with a class). They may be used to invoke the method within the object, and as a block associated with an iterator. They may also be unbound from one object (creating an UnboundMethod
) and bound to another.
class Thing def square(n) n*n end end thing = Thing.new meth = thing.method(:square) meth.call(9) #=> 81 [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9] [ 1, 2, 3 ].each(&method(:puts)) #=> prints 1, 2, 3 require 'date' %w[2017-03-01 2017-03-02].collect(&Date.method(:parse)) #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
Ruby supports two forms of objectified methods. Class
Method
is used to represent methods that are associated with a particular object: these method objects are bound to that object. Bound method objects for an object can be created using Object#method
.
Ruby also supports unbound methods; methods objects that are not associated with a particular object. These can be created either by calling Module#instance_method
or by calling unbind on a bound method object. The result of both of these is an UnboundMethod
object.
Unbound methods can only be called after they are bound to an object. That object must be a kind_of? the method’s original class.
class Square def area @side * @side end def initialize(side) @side = side end end area_un = Square.instance_method(:area) s = Square.new(12) area = area_un.bind(s) area.call #=> 144
Unbound methods are a reference to the method at the time it was objectified: subsequent changes to the underlying class will not affect the unbound method.
class Test def test :original end end um = Test.instance_method(:test) class Test def test :modified end end t = Test.new t.test #=> :modified um.bind(t).call #=> :original
Provides mathematical functions.
Example:
require "bigdecimal/math" include BigMath a = BigDecimal((PI(100)/2).to_s) puts sin(a,100) # => 0.99999999999999999999......e0
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
.
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:
Represents an alternation pattern in pattern matching.
foo => bar | baz ^^^^^^^^^
Represents accessing a constant through a path of ‘::` operators.
Foo::Bar ^^^^^^^^
Represents assigning to a constant path using an operator that isn’t ‘=`.
Parent::Child += value ^^^^^^^^^^^^^^^^^^^^^^
Represents an optional keyword parameter to a method, block, or lambda definition.
def a(b: 1) ^^^^ end
Represents an optional parameter to a method, block, or lambda definition.
def a(b = 1) ^^^^^ end