Results for: "pstore"

Performs a test on one or both of the filesystem entities at the given paths path0 and path1:

The tests:

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 in the current namespace or one of its ancestors.

autoload(:B, "b")
autoload?(:B)            #=> "b"

module C
  autoload(:D, "d")
  autoload?(:D)          #=> "d"
  autoload?(:B)          #=> nil
end

class E
  autoload(:F, "f")
  autoload?(:F)          #=> "f"
  autoload?(:B)          #=> "b"
end

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:

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:

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:

This method has potential security vulnerabilities if called with untrusted input; see Command Injection.

Returns:

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:

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('exit')                                  # => 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('exit')                             # => 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:

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. This form does not use the shell; see Arguments args for caveats.

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.

Returns an array containing the items in self:

(0..4).to_a # => [0, 1, 2, 3, 4]

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:

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 the result of applying a reducer to an initial value and the first element of the Enumerable. It then takes the result and applies the function to it and the second element of the collection, and so on. The return value is the result returned by the final call to the function.

You can think of

[ a, b, c, d ].inject(i) { |r, v| fn(r, v) }

as being

fn(fn(fn(fn(i, a), b), c), d)

In a way the inject function injects the function between the elements of the enumerable.

inject is aliased as reduce. You use it when you want to reduce a collection to a single value.

The Calling Sequences

Let’s start with the most verbose:

enum.inject(initial_value) do |result, next_value|
  # do something with +result+ and +next_value+
  # the value returned by the block becomes the
  # value passed in to the next iteration
  # as +result+
end

For example:

product = [ 2, 3, 4 ].inject(1) do |result, next_value|
  result * next_value
end
product #=> 24

When this runs, the block is first called with 1 (the initial value) and 2 (the first element of the array). The block returns 1*2, so on the next iteration the block is called with 2 (the previous result) and 3. The block returns 6, and is called one last time with 6 and 4. The result of the block, 24 becomes the value returned by inject. This code returns the product of the elements in the enumerable.

First Shortcut: Default Initial value

In the case of the previous example, the initial value, 1, wasn’t really necessary: the calculation of the product of a list of numbers is self-contained.

In these circumstances, you can omit the initial_value parameter. inject will then initially call the block with the first element of the collection as the result parameter and the second element as the next_value.

[ 2, 3, 4 ].inject do |result, next_value|
  result * next_value
end

This shortcut is convenient, but can only be used when the block produces a result which can be passed back to it as a first parameter.

Here’s an example where that’s not the case: it returns a hash where the keys are words and the values are the number of occurrences of that word in the enumerable.

freqs = File.read("README.md")
  .scan(/\w{2,}/)
  .reduce(Hash.new(0)) do |counts, word|
    counts[word] += 1
    counts
  end
freqs #=> {"Actions"=>4,
           "Status"=>5,
           "MinGW"=>3,
           "https"=>27,
           "github"=>10,
           "com"=>15, ...

Note that the last line of the block is just the word counts. This ensures the return value of the block is the result that’s being calculated.

Second Shortcut: a Reducer function

A reducer function is a function that takes a partial result and the next value, returning the next partial result. The block that is given to inject is a reducer.

You can also write a reducer as a function and pass the name of that function (as a symbol) to inject. However, for this to work, the function

  1. Must be defined on the type of the result value

  2. Must accept a single parameter, the next value in the collection, and

  3. Must return an updated result which will also implement the function.

Here’s an example that adds elements to a string. The two calls invoke the functions String#concat and String#+ on the result so far, passing it the next value.

s = [ "cat", " ", "dog" ].inject("", :concat)
s #=> "cat dog"
s = [ "cat", " ", "dog" ].inject("The result is:", :+)
s #=> "The result is: cat dog"

Here’s a more complex example when the result object maintains state of a different type to the enumerable elements.

class Turtle

  def initialize
    @x = @y = 0
  end

  def move(dir)
    case dir
    when "n" then @y += 1
    when "s" then @y -= 1
    when "e" then @x += 1
    when "w" then @x -= 1
    end
    self
  end
end

position = "nnneesw".chars.reduce(Turtle.new, :move)
position  #=>> #<Turtle:0x00000001052f4698 @y=2, @x=1>

Third Shortcut: Reducer With no Initial Value

If your reducer returns a value that it can accept as a parameter, then you don’t have to pass in an initial value. Here :* is the name of the times function:

product = [ 2, 3, 4 ].inject(:*)
product # => 24

String concatenation again:

s = [ "cat", " ", "dog" ].inject(:+)
s #=> "cat dog"

And an example that converts a hash to an array of two-element subarrays.

nested = {foo: 0, bar: 1}.inject([], :push)
nested # => [[:foo, 0], [:bar, 1]]

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 a list of the supported category symbols.

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.

Search took: 3ms  ·  Total Results: 4418