Equivalent to method Kernel#gets
, except that it raises an exception if called at end-of-stream:
$ cat t.txt | ruby -e "p readlines; readline" ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"] in `readline': end of file reached (EOFError)
Optional keyword argument chomp
specifies whether line separators are to be omitted.
Returns an array containing the lines returned by calling Kernel#gets
until the end-of-stream is reached; (see Line IO).
With only string argument sep
given, returns the remaining lines as determined by line separator sep
, or nil
if none; see Line Separator:
# Default separator. $ cat t.txt | ruby -e "p readlines" ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"] # Specified separator. $ cat t.txt | ruby -e "p readlines 'li'" ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"] # Get-all separator. $ cat t.txt | ruby -e "p readlines nil" ["First line\nSecond line\n\nFourth line\nFifth line\n"] # Get-paragraph separator. $ cat t.txt | ruby -e "p readlines ''" ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]
With only integer argument limit
given, limits the number of bytes in the line; see Line Limit:
$cat t.txt | ruby -e "p readlines 10" ["First line", "\n", "Second lin", "e\n", "\n", "Fourth lin", "e\n", "Fifth line", "\n"] $cat t.txt | ruby -e "p readlines 11" ["First line\n", "Second line", "\n", "\n", "Fourth line", "\n", "Fifth line\n"] $cat t.txt | ruby -e "p readlines 12" ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
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:
$ cat t.txt | ruby -e "p readlines(chomp: true)" ["First line", "Second line", "", "Fourth line", "Fifth line"]
Optional keyword arguments enc_opts
specify encoding options; see Encoding options.
Returns an integer converted from object
.
Tries to convert object
to an integer using to_int
first and to_i
second; see below for exceptions.
With a non-zero base
, object
must be a string or convertible to a string.
With integer argument object
given, returns object
:
Integer(1) # => 1 Integer(-1) # => -1
With floating-point argument object
given, returns object
truncated to an integer:
Integer(1.9) # => 1 # Rounds toward zero. Integer(-1.9) # => -1 # Rounds toward zero.
With string argument object
and zero base
given, returns object
converted to an integer in base 10:
Integer('100') # => 100 Integer('-100') # => -100
With base
zero, string object
may contain leading characters to specify the actual base (radix indicator):
Integer('0100') # => 64 # Leading '0' specifies base 8. Integer('0b100') # => 4 # Leading '0b', specifies base 2. Integer('0x100') # => 256 # Leading '0x' specifies base 16.
With a positive base
(in range 2..36) given, returns object
converted to an integer in the given base:
Integer('100', 2) # => 4 Integer('100', 8) # => 64 Integer('-100', 16) # => -256
With a negative base
(in range -36..-2) given, returns object
converted to an integer in the radix indicator if exists or -base
:
Integer('0x100', -2) # => 256 Integer('100', -2) # => 4 Integer('0b100', -8) # => 4 Integer('100', -8) # => 64 Integer('0o100', -10) # => 64 Integer('100', -10) # => 100
base
-1 is equal the -10 case.
When converting strings, surrounding whitespace and embedded underscores are allowed and ignored:
Integer(' 100 ') # => 100 Integer('-1_0_0', 16) # => -256
Examples with object
of various other classes:
Integer(Rational(9, 10)) # => 0 # Rounds toward zero. Integer(Complex(2, 0)) # => 2 # Imaginary part must be zero. Integer(Time.now) # => 1650974042
With optional keyword argument exception
given as true
(the default):
Raises TypeError
if object
does not respond to to_int
or to_i
.
Raises TypeError
if object
is nil
.
Raise ArgumentError
if object
is an invalid string.
With exception
given as false
, an exception of any kind is suppressed and nil
is returned.
Returns the string resulting from formatting objects
into format_string
.
For details on format_string
, see Format Specifications.
Returns the string resulting from formatting objects
into format_string
.
For details on format_string
, see Format Specifications.
Returns a string converted from object
.
Tries to convert object
to a string using to_str
first and to_s
second:
String([0, 1, 2]) # => "[0, 1, 2]" String(0..5) # => "0..5" String({foo: 0, bar: 1}) # => "{:foo=>0, :bar=>1}"
Raises TypeError
if object
cannot be converted to a string.
Returns the first element for which the block returns a truthy value.
With a block given, calls the block with successive elements of the collection; returns the first element for which the block returns a truthy value:
(0..9).find {|element| element > 2} # => 3
If no such element is found, calls if_none_proc
and returns its return value.
(0..9).find(proc {false}) {|element| element > 12} # => false {foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?('b') } # => [:bar, 1] {foo: 0, bar: 1, baz: 2}.find(proc {[]}) {|key, value| key.start_with?('c') } # => []
With no block given, returns an Enumerator
.
Returns an array of objects returned by the block.
With a block given, calls the block with successive elements; returns an array of the objects returned by the block:
(0..4).map {|i| i*i } # => [0, 1, 4, 9, 16] {foo: 0, bar: 1, baz: 2}.map {|key, value| value*2} # => [0, 2, 4]
With no block given, returns an Enumerator
.
Returns an object formed from operands via either:
A method named by symbol
.
A block to which each operand is passed.
With method-name argument symbol
, combines operands using the method:
# Sum, without initial_operand. (1..4).inject(:+) # => 10 # Sum, with initial_operand. (1..4).inject(10, :+) # => 20
With a block, passes each operand to the block:
# Sum of squares, without initial_operand. (1..4).inject {|sum, n| sum + n*n } # => 30 # Sum of squares, with initial_operand. (1..4).inject(2) {|sum, n| sum + n*n } # => 32
Operands
If argument initial_operand
is not given, the operands for inject
are simply the elements of self
. Example calls and their operands:
(1..4).inject(:+)
[1, 2, 3, 4]
.
(1...4).inject(:+)
[1, 2, 3]
.
('a'..'d').inject(:+)
['a', 'b', 'c', 'd']
.
('a'...'d').inject(:+)
['a', 'b', 'c']
.
Examples with first operand (which is self.first
) of various types:
# Integer. (1..4).inject(:+) # => 10 # Float. [1.0, 2, 3, 4].inject(:+) # => 10.0 # Character. ('a'..'d').inject(:+) # => "abcd" # Complex. [Complex(1, 2), 3, 4].inject(:+) # => (8+2i)
If argument initial_operand
is given, the operands for inject
are that value plus the elements of self
. Example calls their operands:
(1..4).inject(10, :+)
[10, 1, 2, 3, 4]
.
(1...4).inject(10, :+)
[10, 1, 2, 3]
.
('a'..'d').inject('e', :+)
['e', 'a', 'b', 'c', 'd']
.
('a'...'d').inject('e', :+)
['e', 'a', 'b', 'c']
.
Examples with initial_operand
of various types:
# Integer. (1..4).inject(2, :+) # => 12 # Float. (1..4).inject(2.0, :+) # => 12.0 # String. ('a'..'d').inject('foo', :+) # => "fooabcd" # Array. %w[a b c].inject(['x'], :push) # => ["x", "a", "b", "c"] # Complex. (1..4).inject(Complex(2, 2), :+) # => (12+2i)
Combination by Given Method
If the method-name argument symbol
is given, the operands are combined by that method:
The first and second operands are combined.
That result is combined with the third operand.
That result is combined with the fourth operand.
And so on.
The return value from inject
is the result of the last combination.
This call to inject
computes the sum of the operands:
(1..4).inject(:+) # => 10
Examples with various methods:
# Integer addition. (1..4).inject(:+) # => 10 # Integer multiplication. (1..4).inject(:*) # => 24 # Character range concatenation. ('a'..'d').inject('', :+) # => "abcd" # String array concatenation. %w[foo bar baz].inject('', :+) # => "foobarbaz" # Hash update. h = [{foo: 0, bar: 1}, {baz: 2}, {bat: 3}].inject(:update) h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3} # Hash conversion to nested arrays. h = {foo: 0, bar: 1}.inject([], :push) h # => [[:foo, 0], [:bar, 1]]
Combination by Given Block
If a block is given, the operands are passed to the block:
The first call passes the first and second operands.
The second call passes the result of the first call, along with the third operand.
The third call passes the result of the second call, along with the fourth operand.
And so on.
The return value from inject
is the return value from the last block call.
This call to inject
gives a block that writes the memo and element, and also sums the elements:
(1..4).inject do |memo, element| p "Memo: #{memo}; element: #{element}" memo + element end # => 10
Output:
"Memo: 1; element: 2" "Memo: 3; element: 3" "Memo: 6; element: 4"
Returns whether for any element object == element
:
(1..4).include?(2) # => true (1..4).include?(5) # => false (1..4).include?('2') # => false %w[a b c d].include?('b') # => true %w[a b c d].include?('2') # => false {foo: 0, bar: 1, baz: 2}.include?(:foo) # => true {foo: 0, bar: 1, baz: 2}.include?('foo') # => false {foo: 0, bar: 1, baz: 2}.include?(0) # => false
Returns an enumerator object generated from this enumerator and given enumerables.
e = (1..3).chain([4, 5]) e.to_a #=> [1, 2, 3, 4, 5]
Computes the sine of decimal
to the specified number of digits of precision, numeric
.
If decimal
is Infinity or NaN, returns NaN.
BigMath.sin(BigMath.PI(5)/4, 5).to_s #=> "0.70710678118654752440082036563292800375e0"
Returns true if coverage stats are currently being collected (after Coverage.start
call, but before Coverage.result
call)
Returns the short user name of the currently logged in user. Unfortunately, it is often rather easy to fool ::getlogin
.
Avoid ::getlogin
for security-related purposes.
If ::getlogin
fails, try ::getpwuid
.
See the unix manpage for getpwuid(3)
for more detail.
e.g.
Etc.getlogin -> 'guest'
Allocate size
bytes of memory and return the integer memory address for the allocated memory.
Returns the log priority mask in effect. The mask is not reset by opening or closing syslog.
Sets the log priority mask. A method LOG_UPTO is defined to make it easier to set mask values. Example:
Syslog.mask = Syslog::LOG_UPTO(Syslog::LOG_ERR)
Alternatively, specific priorities can be selected and added together using binary OR. Example:
Syslog.mask = Syslog::LOG_MASK(Syslog::LOG_ERR) | Syslog::LOG_MASK(Syslog::LOG_CRIT)
The priority mask persists through calls to open() and close().
Returns an inspect() string summarizing the object state.
Returns self, for backward compatibility.
Decompresses string
. Raises a Zlib::NeedDict
exception if a preset dictionary is needed for decompression.
This method is almost equivalent to the following code:
def inflate(string) zstream = Zlib::Inflate.new buf = zstream.inflate(string) zstream.finish zstream.close buf end
See also Zlib.deflate
Returns true
if filepath
points to a symbolic link, false
otherwise:
symlink = File.symlink('t.txt', 'symlink') File.symlink?('symlink') # => true File.symlink?('t.txt') # => false
Invokes the block with a Benchmark::Report object, which may be used to collect and report on the results of individual benchmark tests. Reserves label_width
leading spaces for labels on each line. Prints caption
at the top of the report, and uses format
to format each line. (Note: caption
must contain a terminating newline character, see the default Benchmark::Tms::CAPTION for an example.)
Returns an array of Benchmark::Tms
objects.
If the block returns an array of Benchmark::Tms
objects, these will be used to format additional lines of output. If labels
parameter are given, these are used to label these extra lines.
Note: Other methods provide a simpler interface to this one, and are suitable for nearly all benchmarking requirements. See the examples in Benchmark
, and the bm
and bmbm
methods.
Example:
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
Generates:
user system total real for: 0.970000 0.000000 0.970000 ( 0.970493) times: 0.990000 0.000000 0.990000 ( 0.989542) upto: 0.970000 0.000000 0.970000 ( 0.972854) >total: 2.930000 0.000000 2.930000 ( 2.932889) >avg: 0.976667 0.000000 0.976667 ( 0.977630)
Invokes the block with a Benchmark::Report object, which may be used to collect and report on the results of individual benchmark tests. Reserves label_width
leading spaces for labels on each line. Prints caption
at the top of the report, and uses format
to format each line. (Note: caption
must contain a terminating newline character, see the default Benchmark::Tms::CAPTION for an example.)
Returns an array of Benchmark::Tms
objects.
If the block returns an array of Benchmark::Tms
objects, these will be used to format additional lines of output. If labels
parameter are given, these are used to label these extra lines.
Note: Other methods provide a simpler interface to this one, and are suitable for nearly all benchmarking requirements. See the examples in Benchmark
, and the bm
and bmbm
methods.
Example:
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
Generates:
user system total real for: 0.970000 0.000000 0.970000 ( 0.970493) times: 0.990000 0.000000 0.990000 ( 0.989542) upto: 0.970000 0.000000 0.970000 ( 0.972854) >total: 2.930000 0.000000 2.930000 ( 2.932889) >avg: 0.976667 0.000000 0.976667 ( 0.977630)
The path where gem executables are to be installed.
The path were rubygems plugins are to be installed.