Uses the character cmd
to perform various tests on file1
(first table below) or on file1
and file2
(second table).
File
tests on a single file:
Cmd Returns Meaning "A" | Time | Last access time for file1 "b" | boolean | True if file1 is a block device "c" | boolean | True if file1 is a character device "C" | Time | Last change time for file1 "d" | boolean | True if file1 exists and is a directory "e" | boolean | True if file1 exists "f" | boolean | True if file1 exists and is a regular file "g" | boolean | True if file1 has the setgid bit set "G" | boolean | True if file1 exists and has a group | | ownership equal to the caller's group "k" | boolean | True if file1 exists and has the sticky bit set "l" | boolean | True if file1 exists and is a symbolic link "M" | Time | Last modification time for file1 "o" | boolean | True if file1 exists and is owned by | | the caller's effective uid "O" | boolean | True if file1 exists and is owned by | | the caller's real uid "p" | boolean | True if file1 exists and is a fifo "r" | boolean | True if file1 is readable by the effective | | uid/gid of the caller "R" | boolean | True if file is readable by the real | | uid/gid of the caller "s" | int/nil | If file1 has nonzero size, return the size, | | otherwise return nil "S" | boolean | True if file1 exists and is a socket "u" | boolean | True if file1 has the setuid bit set "w" | boolean | True if file1 exists and is writable by | | the effective uid/gid "W" | boolean | True if file1 exists and is writable by | | the real uid/gid "x" | boolean | True if file1 exists and is executable by | | the effective uid/gid "X" | boolean | True if file1 exists and is executable by | | the real uid/gid "z" | boolean | True if file1 exists and has a zero length
Tests that take two files:
"-" | boolean | True if file1 and file2 are identical "=" | boolean | True if the modification times of file1 | | and file2 are equal "<" | boolean | True if the modification time of file1 | | is prior to that of file2 ">" | boolean | True if the modification time of file1 | | is after that of file2
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.
Registers _filename_ to be loaded (using Kernel::require) the first time that _const_ (which may be a String or a symbol) is accessed. autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
If const is defined as autoload, the file name to be loaded is replaced with filename. If const is defined but not as autoload, does nothing.
Returns filename to be loaded if name is registered as autoload
.
autoload(:B, "b") autoload?(:B) #=> "b"
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.
Creates a child process.
With a block given, runs the block in the child process; on block exit, the child terminates with a status of zero:
puts "Before the fork: #{Process.pid}" fork do puts "In the child process: #{Process.pid}" end # => 382141 puts "After the fork: #{Process.pid}"
Output:
Before the fork: 420496 After the fork: 420496 In the child process: 420520
With no block given, the fork
call returns twice:
Once in the parent process, returning the pid of the child process.
Once in the child process, returning nil
.
Example:
puts "This is the first line before the fork (pid #{Process.pid})" puts fork puts "This is the second line after the fork (pid #{Process.pid})"
Output:
This is the first line before the fork (pid 420199) 420223 This is the second line after the fork (pid 420199) This is the second line after the fork (pid 420223)
In either case, the child process may exit using Kernel.exit!
to avoid the call to Kernel#at_exit
.
To avoid zombie processes, the parent process should call either:
Process.wait
, to collect the termination statuses of its children.
Process.detach
, to register disinterest in their status.
The thread calling fork
is the only thread in the created child process; fork
doesn’t copy other threads.
Note that method fork
is available on some platforms, but not on others:
Process.respond_to?(:fork) # => true # Would be false on some.
If not, you may use ::spawn instead of fork
.
Creates a new child process by doing one of the following in that process:
Passing string command_line
to the shell.
Invoking the executable at exe_path
.
This method has potential security vulnerabilities if called with untrusted input; see Command Injection.
Returns:
true
if the command exits with status zero.
false
if the exit status is a non-zero integer.
nil
if the command could not execute.
Raises an exception (instead of returning false
or nil
) if keyword argument exception
is set to true
.
Assigns the command’s error status to $?
.
The new process is created using the system system call; it may inherit some of its environment from the calling program (possibly including open file descriptors).
Argument env
, if given, is a hash that affects ENV
for the new process; see Execution Environment.
Argument options
is a hash of options for the new process; see Execution Options.
The first required argument is one of the following:
command_line
if it is a string, and if it begins with a shell reserved word or special built-in, or if it contains one or more meta characters.
exe_path
otherwise.
Argument command_line
String argument command_line
is a command line to be passed to a shell; it must begin with a shell reserved word, begin with a special built-in, or contain meta characters:
system('if true; then echo "Foo"; fi') # => true # Shell reserved word. system('echo') # => true # Built-in. system('date > /tmp/date.tmp') # => true # Contains meta character. system('date > /nop/date.tmp') # => false system('date > /nop/date.tmp', exception: true) # Raises RuntimeError.
Assigns the command’s error status to $?
:
system('echo') # => true # Built-in. $? # => #<Process::Status: pid 640610 exit 0> system('date > /nop/date.tmp') # => false $? # => #<Process::Status: pid 640742 exit 2>
The command line may also contain arguments and options for the command:
system('echo "Foo"') # => true
Output:
Foo
See Execution Shell for details about the shell.
Raises an exception if the new process could not execute.
Argument exe_path
Argument exe_path
is one of the following:
The string path to an executable to be called.
A 2-element array containing the path to an executable and the string to be used as the name of the executing process.
Example:
system('/usr/bin/date') # => true # Path to date on Unix-style system. system('foo') # => nil # Command failed.
Output:
Mon Aug 28 11:43:10 AM CDT 2023
Assigns the command’s error status to $?
:
system('/usr/bin/date') # => true $? # => #<Process::Status: pid 645605 exit 0> system('foo') # => nil $? # => #<Process::Status: pid 645608 exit 127>
Ruby invokes the executable directly, with no shell and no shell expansion:
system('doesnt_exist') # => nil
If one or more args
is given, each is an argument or option to be passed to the executable:
system('echo', 'C*') # => true system('echo', 'hello', 'world') # => true
Output:
C* hello world
Raises an exception if the new process could not execute.
Terminates execution immediately, effectively by calling Kernel.exit(false)
.
If string argument msg
is given, it is written to STDERR prior to termination; otherwise, if an exception was raised, prints its message and backtrace.
When self
consists of 2-element arrays, returns a hash each of whose entries is the key-value pair formed from one of those arrays:
[[:foo, 0], [:bar, 1], [:baz, 2]].to_h # => {:foo=>0, :bar=>1, :baz=>2}
When a block is given, the block is called with each element of self
; the block should return a 2-element array which becomes a key-value pair in the returned hash:
(0..3).to_h {|i| [i, i ** 2]} # => {0=>0, 1=>1, 2=>4, 3=>9}
Raises an exception if an element of self
is not a 2-element array, and a block is not passed.
Returns an array containing the sorted elements of self
. The ordering of equal elements is indeterminate and may be unstable.
With no block given, the sort compares using the elements’ own method <=>
:
%w[b c a d].sort # => ["a", "b", "c", "d"] {foo: 0, bar: 1, baz: 2}.sort # => [[:bar, 1], [:baz, 2], [:foo, 0]]
With a block given, comparisons in the block determine the ordering. The block is called with two elements a
and b
, and must return:
A negative integer if a < b
.
Zero if a == b
.
A positive integer if a > b
.
Examples:
a = %w[b c a d] a.sort {|a, b| b <=> a } # => ["d", "c", "b", "a"] h = {foo: 0, bar: 1, baz: 2} h.sort {|a, b| b <=> a } # => [[:foo, 0], [:baz, 2], [:bar, 1]]
See also sort_by
. It implements a Schwartzian transform which is useful when key computation or comparison is expensive.
Returns an array of objects based elements of self
that match the given pattern.
With no block given, returns an array containing each element for which pattern === element
is true
:
a = ['foo', 'bar', 'car', 'moo'] a.grep(/ar/) # => ["bar", "car"] (1..10).grep(3..8) # => [3, 4, 5, 6, 7, 8] ['a', 'b', 0, 1].grep(Integer) # => [0, 1]
With a block given, calls the block with each matching element and returns an array containing each object returned by the block:
a = ['foo', 'bar', 'car', 'moo'] a.grep(/ar/) {|element| element.upcase } # => ["BAR", "CAR"]
Related: grep_v
.
Returns an array of objects based on elements of self
that don’t match the given pattern.
With no block given, returns an array containing each element for which pattern === element
is false
:
a = ['foo', 'bar', 'car', 'moo'] a.grep_v(/ar/) # => ["foo", "moo"] (1..10).grep_v(3..8) # => [1, 2, 9, 10] ['a', 'b', 0, 1].grep_v(Integer) # => ["a", "b"]
With a block given, calls the block with each non-matching element and returns an array containing each object returned by the block:
a = ['foo', 'bar', 'car', 'moo'] a.grep_v(/ar/) {|element| element.upcase } # => ["FOO", "MOO"]
Related: grep
.
Returns an array of objects rejected by the block.
With a block given, calls the block with successive elements; returns an array of those elements for which the block returns nil
or false
:
(0..9).reject {|i| i * 2 if i.even? } # => [1, 3, 5, 7, 9] {foo: 0, bar: 1, baz: 2}.reject {|key, value| key if value.odd? } # => {:foo=>0, :baz=>2}
When no block given, returns an Enumerator
.
Related: select
.
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 the first element or elements.
With no argument, returns the first element, or nil
if there is none:
(1..4).first # => 1 %w[a b c].first # => "a" {foo: 1, bar: 1, baz: 2}.first # => [:foo, 1] [].first # => nil
With integer argument n
, returns an array containing the first n
elements that exist:
(1..4).first(2) # => [1, 2] %w[a b c d].first(3) # => ["a", "b", "c"] %w[a b c d].first(50) # => ["a", "b", "c", "d"] {foo: 1, bar: 1, baz: 2}.first(2) # => [[:foo, 1], [:bar, 1]] [].first(2) # => []
Returns true if coverage measurement is supported for the given mode.
The mode should be one of the following symbols: :lines
, :oneshot_lines
, :branches
, :methods
, :eval
.
Example:
Coverage.supported?(:lines) #=> true Coverage.supported?(:all) #=> false
Enables the coverage measurement. See the documentation of Coverage
class in detail. This is equivalent to Coverage.setup
and Coverage.resume
.
Start/resume the coverage measurement.
Caveat: Currently, only process-global coverage measurement is supported. You cannot measure per-thread coverage. If your process has multiple thread, using Coverage.resume
/suspend to capture code coverage executed from only a limited code block, may yield misleading results.
Returns a hash that contains filename as key and coverage array as value. If clear
is true, it clears the counters to zero. If stop
is true, it disables coverage measurement.
Returns the state of the coverage measurement.
Resets the process of reading the /etc/group
file, so that the next call to ::getgrent
will return the first entry again.
Ends the process of scanning through the /etc/group
file begun by ::getgrent
, and closes the file.