Returns the current line number for the stream; see Line Number.
Sets and returns the line number for the stream; see Line Number.
Reads and returns all remaining line from the stream; does not modify $_
. See Line IO.
With no arguments given, returns lines as determined by line separator $/
, or nil
if none:
f = File.new('t.txt') f.readlines # => ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"] f.readlines # => [] f.close
With only string argument sep
given, returns lines as determined by line separator sep
, or nil
if none; see Line Separator:
f = File.new('t.txt') f.readlines('li') # => ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"] f.close
The two special values for sep
are honored:
f = File.new('t.txt') # Get all into one string. f.readlines(nil) # => ["First line\nSecond line\n\nFourth line\nFifth line\n"] # Get paragraphs (up to two line separators). f.rewind f.readlines('') # => ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"] f.close
With only integer argument limit
given, limits the number of bytes in each line; see Line Limit:
f = File.new('t.txt') f.readlines(8) # => ["First li", "ne\n", "Second l", "ine\n", "\n", "Fourth l", "ine\n", "Fifth li", "ne\n"] f.close
With arguments sep
and limit
given, combines the two behaviors (see Line Separator and Line Limit).
Optional keyword argument chomp
specifies whether line separators are to be omitted:
f = File.new('t.txt') f.readlines(chomp: true) # => ["First line", "Second line", "", "Fourth line", "Fifth line"] f.close
Writes each of the given objects
to self
, which must be opened for writing (see Access Modes); returns the total number bytes written; each of objects
that is not a string is converted via method to_s
:
$stdout.write('Hello', ', ', 'World!', "\n") # => 14 $stdout.write('foo', :bar, 2, "\n") # => 8
Output:
Hello, World! foobar2
Related: IO#read
.
Pushes back (“unshifts”) the given data onto the stream’s buffer, placing the data so that it is next to be read; returns nil
. See Byte IO.
Note that:
Calling the method has no effect with unbuffered reads (such as IO#sysread
).
Calling rewind
on the stream discards the pushed-back data.
When argument integer
is given, uses only its low-order byte:
File.write('t.tmp', '012') f = File.open('t.tmp') f.ungetbyte(0x41) # => nil f.read # => "A012" f.rewind f.ungetbyte(0x4243) # => nil f.read # => "C012" f.close
When argument string
is given, uses all bytes:
File.write('t.tmp', '012') f = File.open('t.tmp') f.ungetbyte('A') # => nil f.read # => "A012" f.rewind f.ungetbyte('BCDE') # => nil f.read # => "BCDE012" f.close
Pushes back (“unshifts”) the given data onto the stream’s buffer, placing the data so that it is next to be read; returns nil
. See Character IO.
Note that:
Calling the method has no effect with unbuffered reads (such as IO#sysread
).
Calling rewind
on the stream discards the pushed-back data.
When argument integer
is given, interprets the integer as a character:
File.write('t.tmp', '012') f = File.open('t.tmp') f.ungetc(0x41) # => nil f.read # => "A012" f.rewind f.ungetc(0x0442) # => nil f.getc.ord # => 1090 f.close
When argument string
is given, uses all characters:
File.write('t.tmp', '012') f = File.open('t.tmp') f.ungetc('A') # => nil f.read # => "A012" f.rewind f.ungetc("\u0442\u0435\u0441\u0442") # => nil f.getc.ord # => 1090 f.getc.ord # => 1077 f.getc.ord # => 1089 f.getc.ord # => 1090 f.close
Repositions the stream to its beginning, setting both the position and the line number to zero; see Position and Line Number:
f = File.open('t.txt') f.tell # => 0 f.lineno # => 0 f.gets # => "First line\n" f.tell # => 12 f.lineno # => 1 f.rewind # => 0 f.tell # => 0 f.lineno # => 0 f.close
Note that this method cannot be used with streams such as pipes, ttys, and sockets.
Sets the stream’s data mode as binary (see Data Mode).
A stream’s data mode may not be changed from binary to text.
Returns true
if the stream is on binary mode, false
otherwise. See Data Mode.
Returns a string representation of self
:
f = File.open('t.txt') f.inspect # => "#<File:t.txt>" f.close
Reads a line as with IO#gets
, but raises EOFError
if already at end-of-stream.
Optional keyword argument chomp
specifies whether line separators are to be omitted.
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
Returns the object that defines the beginning of self
.
(1..4).begin # => 1 (..2).begin # => nil
Related: Range#first
, Range#end
.
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 the minimum value in self
, using method #<=>
or a given block for comparison.
With no argument and no block given, returns the minimum-valued element of self
.
(1..4).min # => 1 ('a'..'d').min # => "a" (-4..-1).min # => -4
With non-negative integer argument n
given, and no block given, returns the n
minimum-valued elements of self
in an array:
(1..4).min(2) # => [1, 2] ('a'..'d').min(2) # => ["a", "b"] (-4..-1).min(2) # => [-4, -3] (1..4).min(50) # => [1, 2, 3, 4]
If a block is given, it is called:
First, with the first two element of self
.
Then, sequentially, with the so-far minimum value and the next element of self
.
To illustrate:
(1..4).min {|a, b| p [a, b]; a <=> b } # => 1
Output:
[2, 1] [3, 1] [4, 1]
With no argument and a block given, returns the return value of the last call to the block:
(1..4).min {|a, b| -(a <=> b) } # => 4
With non-negative integer argument n
given, and a block given, returns the return values of the last n
calls to the block in an array:
(1..4).min(2) {|a, b| -(a <=> b) } # => [4, 3] (1..4).min(50) {|a, b| -(a <=> b) } # => [4, 3, 2, 1]
Returns an empty array if n
is zero:
(1..4).min(0) # => [] (1..4).min(0) {|a, b| -(a <=> b) } # => []
Returns nil
or an empty array if:
The begin value of the range is larger than the end value:
(4..1).min # => nil (4..1).min(2) # => [] (4..1).min {|a, b| -(a <=> b) } # => nil (4..1).min(2) {|a, b| -(a <=> b) } # => []
The begin value of an exclusive range is equal to the end value:
(1...1).min # => nil (1...1).min(2) # => [] (1...1).min {|a, b| -(a <=> b) } # => nil (1...1).min(2) {|a, b| -(a <=> b) } # => []
Raises an exception if either:
self
is a beginless range: (..4)
.
A block is given and self
is an endless range.
Related: Range#max
, Range#minmax
.
Returns a 2-element array containing the minimum and maximum value in self
, either according to comparison method #<=>
or a given block.
With no block given, returns the minimum and maximum values, using #<=>
for comparison:
(1..4).minmax # => [1, 4] (1...4).minmax # => [1, 3] ('a'..'d').minmax # => ["a", "d"] (-4..-1).minmax # => [-4, -1]
With a block given, the block must return an integer:
Negative if a
is smaller than b
.
Zero if a
and b
are equal.
Positive if a
is larger than b
.
The block is called self.size
times to compare elements; returns a 2-element Array
containing the minimum and maximum values from self
, per the block:
(1..4).minmax {|a, b| -(a <=> b) } # => [4, 1]
Returns [nil, nil]
if:
The begin value of the range is larger than the end value:
(4..1).minmax # => [nil, nil] (4..1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
The begin value of an exclusive range is equal to the end value:
(1...1).minmax # => [nil, nil] (1...1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
Raises an exception if self
is a beginless or an endless range.
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 true
if object
is an element of self
, false
otherwise:
(1..4).include?(2) # => true (1..4).include?(5) # => false (1..4).include?(4) # => true (1...4).include?(4) # => false ('a'..'d').include?('b') # => true ('a'..'d').include?('e') # => false ('a'..'d').include?('B') # => false ('a'..'d').include?('d') # => true ('a'...'d').include?('d') # => false
If begin and end are numeric, include?
behaves like cover?
(1..3).include?(1.5) # => true (1..3).cover?(1.5) # => true
But when not numeric, the two methods may differ:
('a'..'d').include?('cc') # => false ('a'..'d').cover?('cc') # => true
Related: Range#cover?
.
Returns the denominator (always positive).
Rational(7).denominator #=> 1 Rational(7, 1).denominator #=> 1 Rational(9, -4).denominator #=> 4 Rational(-2, -10).denominator #=> 5
Returns rat
truncated (toward zero) to a precision of ndigits
decimal digits (default: 0).
When the precision is negative, the returned value is an integer with at least ndigits.abs
trailing zeros.
Returns a rational when ndigits
is positive, otherwise returns an integer.
Rational(3).truncate #=> 3 Rational(2, 3).truncate #=> 0 Rational(-3, 2).truncate #=> -1 # decimal - 1 2 3 . 4 5 6 # ^ ^ ^ ^ ^ ^ # precision -3 -2 -1 0 +1 +2 Rational('-123.456').truncate(+1).to_f #=> -123.4 Rational('-123.456').truncate(-1) #=> -120
Returns the value as a string for inspection.
Rational(2).inspect #=> "(2/1)" Rational(-8, 6).inspect #=> "(-4/3)" Rational('1/2').inspect #=> "(1/2)"
Returns a nicely-formatted string representation of self
:
/ab+c/ix.inspect # => "/ab+c/ix"
Related: Regexp#to_s
.
Returns true if the set contains the given object.
Note that include?
and member?
do not test member equality using ==
as do other Enumerables.
See also Enumerable#include?