Returns a string representation of self
, formatted according the given +format:
DateTime.now.strftime # => "2022-07-01T11:03:19-05:00"
For other formats, see Formats for Dates and Times:
Works similar to parse
except that instead of using a heuristic to detect the format of the input string, you provide a second argument that describes the format of the string.
Raises ArgumentError
if the date or format is invalid.
If a block is given, the year described in date
is converted by the block. For example:
Time.strptime(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
Below is a list of the formatting options:
The abbreviated weekday name (“Sun”)
The full weekday name (“Sunday”)
The abbreviated month name (“Jan”)
The full month name (“January”)
The preferred local date and time representation
Century (20 in 2009)
Day of the month (01..31)
Date (%m/%d/%y)
Day of the month, blank-padded ( 1..31)
Equivalent to %Y-%m-%d (the ISO 8601 date format)
The last two digits of the commercial year
The week-based year according to ISO-8601 (week 1 starts on Monday and includes January 4)
Equivalent to %b
Hour of the day, 24-hour clock (00..23)
Hour of the day, 12-hour clock (01..12)
Day of the year (001..366)
hour, 24-hour clock, blank-padded ( 0..23)
hour, 12-hour clock, blank-padded ( 0..12)
Millisecond of the second (000..999)
Month of the year (01..12)
Minute of the hour (00..59)
Newline (n)
Fractional seconds digits
Meridian indicator (“AM” or “PM”)
Meridian indicator (“am” or “pm”)
time, 12-hour (same as %I:%M:%S %p)
time, 24-hour (%H:%M)
Number of seconds since 1970-01-01 00:00:00 UTC.
Second of the minute (00..60)
Tab character (t)
time, 24-hour (%H:%M:%S)
Day of the week as a decimal, Monday being 1. (1..7)
Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
VMS date (%e-%b-%Y)
Week number of year according to ISO 8601 (01..53)
Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
Day of the week (Sunday is 0, 0..6)
Preferred representation for the date alone, no time
Preferred representation for the time alone, no date
Year without a century (00..99)
Year which may include century, if provided
Time zone as hour offset from UTC (e.g. +0900)
Time zone name
Literal “%” character
date(1) (%a %b %e %H:%M:%S %Z %Y)
require 'time' Time.strptime("2000-10-31", "%Y-%m-%d") #=> 2000-10-31 00:00:00 -0500
You must require ‘time’ to use this method.
Returns a string representation of self
with subseconds:
t = Time.new(2000, 12, 31, 23, 59, 59, 0.5) t.inspect # => "2000-12-31 23:59:59.5 +000001"
Related: Time#ctime
, Time#to_s
:
t.ctime # => "Sun Dec 31 23:59:59 2000" t.to_s # => "2000-12-31 23:59:59 +0000"
Returns true
if self
is in daylight saving time, false
otherwise:
t = Time.local(2000, 1, 1) # => 2000-01-01 00:00:00 -0600 t.zone # => "Central Standard Time" t.dst? # => false t = Time.local(2000, 7, 1) # => 2000-07-01 00:00:00 -0500 t.zone # => "Central Daylight Time" t.dst? # => true
Returns true
if self
is in daylight saving time, false
otherwise:
t = Time.local(2000, 1, 1) # => 2000-01-01 00:00:00 -0600 t.zone # => "Central Standard Time" t.dst? # => false t = Time.local(2000, 7, 1) # => 2000-07-01 00:00:00 -0500 t.zone # => "Central Daylight Time" t.dst? # => true
Returns the string name of the time zone for self
:
Time.utc(2000, 1, 1).zone # => "UTC" Time.new(2000, 1, 1).zone # => "Central Standard Time"
Returns the number of nanoseconds in the subseconds part of self
in the range (0..999_999_999); lower-order digits are truncated, not rounded:
t = Time.now # => 2022-07-11 15:04:53.3219637 -0500 t.nsec # => 321963700
Related: Time#subsec
(returns exact subseconds).
Returns a string representation of self
, formatted according to the given string format
. See Formats for Dates and Times.
Yields self
within cooked mode.
STDIN.cooked(&:gets)
will read and return a line with echo back and line editing.
You must require ‘io/console’ to use this method.
Enables cooked mode.
If the terminal mode needs to be back, use io.cooked { … }.
You must require ‘io/console’ to use this method.
Tries to set console size. The effect depends on the platform and the running environment.
You must require ‘io/console’ to use this method.
Returns true
if an IO
object is in non-blocking mode.
Enables non-blocking mode on a stream when set to true
, and blocking mode when set to false
.
This method set or clear O_NONBLOCK flag for the file descriptor in ios.
The behavior of most IO
methods is not affected by this flag because they retry system calls to complete their task after EAGAIN and partial read/write. (An exception is IO#syswrite
which doesn’t retry.)
This method can be used to clear non-blocking mode of standard I/O. Since nonblocking methods (read_nonblock
, etc.) set non-blocking mode but they doesn’t clear it, this method is usable as follows.
END { STDOUT.nonblock = false } STDOUT.write_nonblock("foo")
Since the flag is shared across processes and many non-Ruby commands doesn’t expect standard I/O with non-blocking mode, it would be safe to clear the flag before Ruby program exits.
For example following Ruby program leaves STDIN/STDOUT/STDER non-blocking mode. (STDIN, STDOUT and STDERR are connected to a terminal. So making one of them nonblocking-mode effects other two.) Thus cat command try to read from standard input and it causes “Resource temporarily unavailable” error (EAGAIN).
% ruby -e ' STDOUT.write_nonblock("foo\n")'; cat foo cat: -: Resource temporarily unavailable
Clearing the flag makes the behavior of cat command normal. (cat command waits input from standard input.)
% ruby -rio/nonblock -e ' END { STDOUT.nonblock = false } STDOUT.write_nonblock("foo") '; cat foo
Yields self
in non-blocking mode.
When false
is given as an argument, self
is yielded in blocking mode. The original mode is restored after the block is executed.
Returns status information for ios as an object of type File::Stat
.
f = File.new("testfile") s = f.stat "%o" % s.mode #=> "100644" s.blksize #=> 4096 s.atime #=> Wed Apr 09 08:53:54 CDT 2003
Returns a string representation of self
:
f = File.open('t.txt') f.inspect # => "#<File:t.txt>" f.close
Returns a string containing a detailed summary of the keys and values.
Iterates over the elements of range in steps of s
. The iteration is performed by +
operator:
(0..6).step(2) { puts _1 } #=> 1..5 # Prints: 0, 2, 4, 6 # Iterate between two dates in step of 1 day (24 hours) (Time.utc(2022, 2, 24)..Time.utc(2022, 3, 1)).step(24*60*60) { puts _1 } # Prints: # 2022-02-24 00:00:00 UTC # 2022-02-25 00:00:00 UTC # 2022-02-26 00:00:00 UTC # 2022-02-27 00:00:00 UTC # 2022-02-28 00:00:00 UTC # 2022-03-01 00:00:00 UTC
If + step
decreases the value, iteration is still performed when step begin
is higher than the end
:
(0..6).step(-2) { puts _1 } # Prints nothing (6..0).step(-2) { puts _1 } # Prints: 6, 4, 2, 0 (Time.utc(2022, 3, 1)..Time.utc(2022, 2, 24)).step(-24*60*60) { puts _1 } # Prints: # 2022-03-01 00:00:00 UTC # 2022-02-28 00:00:00 UTC # 2022-02-27 00:00:00 UTC # 2022-02-26 00:00:00 UTC # 2022-02-25 00:00:00 UTC # 2022-02-24 00:00:00 UTC
When the block is not provided, and range boundaries and step are Numeric
, the method returns Enumerator::ArithmeticSequence
.
(1..5).step(2) # => ((1..5).step(2)) (1.0..).step(1.5) #=> ((1.0..).step(1.5)) (..3r).step(1/3r) #=> ((..3/1).step((1/3)))
Enumerator::ArithmeticSequence
can be further used as a value object for iteration or slicing of collections (see Array#[]
). There is a convenience method %
with behavior similar to step
to produce arithmetic sequences more expressively:
# Same as (1..5).step(2) (1..5) % 2 # => ((1..5).%(2))
In a generic case, when the block is not provided, Enumerator
is returned:
('a'..).step('b') #=> #<Enumerator: "a"..:step("b")> ('a'..).step('b').take(3) #=> ["a", "ab", "abb"]
If s
is not provided, it is considered 1
for ranges with numeric begin
:
(1..5).step { p _1 } # Prints: 1, 2, 3, 4, 5
For non-Numeric ranges, step absence is an error:
(Time.utc(2022, 3, 1)..Time.utc(2022, 2, 24)).step { p _1 } # raises: step is required for non-numeric ranges (ArgumentError)
For backward compatibility reasons, String
ranges support the iteration both with string step and with integer step. In the latter case, the iteration is performed by calculating the next values with String#succ
:
('a'..'e').step(2) { p _1 } # Prints: a, c, e ('a'..'e').step { p _1 } # Default step 1; prints: a, b, c, d, e
With no argument, returns the first element of self
, if it exists:
(1..4).first # => 1 ('a'..'d').first # => "a"
With non-negative integer argument n
given, returns the first n
elements in an array:
(1..10).first(3) # => [1, 2, 3] (1..10).first(0) # => [] (1..4).first(50) # => [1, 2, 3, 4]
Raises an exception if there is no first element:
(..4).first # Raises RangeError
With no argument, returns the last element of self
, if it exists:
(1..4).last # => 4 ('a'..'d').last # => "d"
Note that last
with no argument returns the end element of self
even if exclude_end?
is true
:
(1...4).last # => 4 ('a'...'d').last # => "d"
With non-negative integer argument n
given, returns the last n
elements in an array:
(1..10).last(3) # => [8, 9, 10] (1..10).last(0) # => [] (1..4).last(50) # => [1, 2, 3, 4]
Note that last
with argument does not return the end element of self
if exclude_end?
it true
:
(1...4).last(3) # => [1, 2, 3] ('a'...'d').last(3) # => ["a", "b", "c"]
Raises an exception if there is no last element:
(1..).last # Raises RangeError
Returns a string representation of self
, including begin.inspect
and end.inspect
:
(1..4).inspect # => "1..4" (1...4).inspect # => "1...4" (1..).inspect # => "1.." (..4).inspect # => "..4"
Note that returns from to_s
and inspect
may differ:
('a'..'d').to_s # => "a..d" ('a'..'d').inspect # => "\"a\"..\"d\""
Related: Range#to_s
.
Returns the count of elements, based on an argument or block criterion, if given.
With no argument and no block given, returns the number of elements:
(1..4).count # => 4 (1...4).count # => 3 ('a'..'d').count # => 4 ('a'...'d').count # => 3 (1..).count # => Infinity (..4).count # => Infinity
With argument object
, returns the number of object
found in self
, which will usually be zero or one:
(1..4).count(2) # => 1 (1..4).count(5) # => 0 (1..4).count('a') # => 0
With a block given, calls the block with each element; returns the number of elements for which the block returns a truthy value:
(1..4).count {|element| element < 3 } # => 2
Related: Range#size
.
Returns a simpler approximation of the value if the optional argument eps
is given (rat-|eps| <= result <= rat+|eps|), self otherwise.
r = Rational(5033165, 16777216) r.rationalize #=> (5033165/16777216) r.rationalize(Rational('0.01')) #=> (3/10) r.rationalize(Rational('0.1')) #=> (1/3)