Results for: "Pathname"

Give the thread scheduler a hint to pass execution to another thread. A running thread may or may not switch, it depends on OS and processor.

Returns the status of thr.

"sleep"

Returned if this thread is sleeping or waiting on I/O

"run"

When this thread is executing

"aborting"

If this thread is aborting

false

When this thread is terminated normally

nil

If terminated with an exception.

Example
a = Thread.new { raise("die now") }
b = Thread.new { Thread.stop }
c = Thread.new { Thread.exit }
d = Thread.new { sleep }
d.kill                  #=> #<Thread:0x401b3678 aborting>
a.status                #=> nil
b.status                #=> "sleep"
c.status                #=> false
d.status                #=> "aborting"
Thread.current.status   #=> "run"

See also the instance methods alive? and stop?

Returns internal information of TracePoint.

The contents of the returned value are implementation-specific and may change in the future.

This method is only for debugging TracePoint itself.

Activates the trace.

Returns true if the trace was enabled. Returns false if the trace was disabled.

Example
trace.enabled?  #=> false
trace.enable    #=> false (previous state)
                #   trace is enabled
trace.enabled?  #=> true
trace.enable    #=> true (previous state)
                #   trace is still enabled

If a block is given, the trace will only be enabled during the block execution. If target and target_line are both nil, then target_thread will default to the current thread if a block is given.

Example
trace.enabled?  #=> false

trace.enable do
  trace.enabled?
  # Only enabled for this block and thread
end

trace.enabled?  #=> false

The target, target_line, and target_thread parameters are used to limit tracing to specified code objects. target should be a code object for which RubyVM::InstructionSequence.of will return an instruction sequence.

Example
t = TracePoint.new(:line) { |tp| p tp }

def m1
  p 1
end

def m2
  p 2
end

t.enable(target: method(:m1))

m1
# Prints #<TracePoint:line test.rb:4 in `m1'>
m2
# Prints nothing

Note: You cannot access event hooks within the enable block.

Example
trace.enable { p tp.lineno }
#=> RuntimeError: access from outside

Returns the current status of the trace.

In (min, max) form, returns min if obj <=> min is less than zero, max if obj <=> max is greater than zero, and obj otherwise.

Example
12.clamp(0, 100)         #=> 12
523.clamp(0, 100)        #=> 100
-3.123.clamp(0, 100)     #=> 0

'd'.clamp('a', 'f')      #=> 'd'
'z'.clamp('a', 'f')      #=> 'f'

If min is nil, it is considered smaller than obj, and if max is nil, it is considered greater than obj.

Example
-20.clamp(0, nil)           #=> 0
523.clamp(nil, 100)         #=> 100

In (range) form, returns range.begin if obj <=> range.begin is less than zero, range.end if obj <=> range.end is greater than zero, and obj otherwise.

Example
12.clamp(0..100)         #=> 12
523.clamp(0..100)        #=> 100
-3.123.clamp(0..100)     #=> 0

'd'.clamp('a'..'f')      #=> 'd'
'z'.clamp('a'..'f')      #=> 'f'

If range.begin is nil, it is considered smaller than obj, and if range.end is nil, it is considered greater than obj.

Example
-20.clamp(0..)           #=> 0
523.clamp(..100)         #=> 100

When range.end is excluded and not nil, an exception is raised.

Example
100.clamp(0...100)       # ArgumentError

Yields self to the block and returns the result of the block.

Example
3.next.then {|x| x**x }.to_s             #=> "256"

A good use of then is value piping in method chains:

Example
require 'open-uri'
require 'json'

construct_url(arguments)
  .then {|url| URI(url).read }
  .then {|response| JSON.parse(response) }

When called without a block, the method returns an Enumerator, which can be used, for example, for conditional circuit-breaking:

Example
# Meets condition, no-op
1.then.detect(&:odd?)            # => 1
# Does not meet condition, drop value
2.then.detect(&:odd?)            # => nil

Returns arg converted to a float. Numeric types are converted directly, and with exception to String and nil, the rest are converted using arg.to_f. Converting a String with invalid characters will result in an ArgumentError. Converting nil generates a TypeError. Exceptions can be suppressed by passing exception: false.

Example
Float(1)                 #=> 1.0
Float("123.456")         #=> 123.456
Float("123.0_badstring") #=> ArgumentError: invalid value for Float(): "123.0_badstring"
Float(nil)               #=> TypeError: can't convert nil into Float
Float("123.0_badstring", exception: false)  #=> nil

Returns the string resulting from formatting objects into format_string.

For details on format_string, see Format Specifications.

Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.

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 the process ID (pid) of the new process, without waiting for it to complete.

To avoid zombie processes, the parent process should call either:

The new process is created using the exec 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:

Example
spawn('if true; then echo "Foo"; fi') # => 798847 # Shell reserved word.
Process.wait                          # => 798847
spawn('exit')                         # => 798848 # Built-in.
Process.wait                          # => 798848
spawn('date > /tmp/date.tmp')         # => 798879 # Contains meta character.
Process.wait                          # => 798849
spawn('date > /nop/date.tmp')         # => 798882 # Issues error message.
Process.wait                          # => 798882

The command line may also contain arguments and options for the command:

Example
spawn('echo "Foo"') # => 799031
Process.wait        # => 799031

Output:

Example
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:

Ruby invokes the executable directly. This form does not use the shell; see Arguments args for caveats.

If one or more args is given, each is an argument or option to be passed to the executable:

Example
spawn('echo', 'C*')             # => 799392
Process.wait                    # => 799392
spawn('echo', 'hello', 'world') # => 799393
Process.wait                    # => 799393

Output:

C*
hello world

Raises an exception if the new process could not execute.

Deprecated. Use block_given? instead.

catch executes its block. If throw is not called, the block executes normally, and catch returns the value of the last expression evaluated.

Example
catch(1) { 123 }            # => 123

If throw(tag2, val) is called, Ruby searches up its stack for a catch block whose tag has the same object_id as tag2. When found, the block stops executing and returns val (or nil if no second argument was given to throw).

Example
catch(1) { throw(1, 456) }  # => 456
catch(1) { throw(1) }       # => nil

When tag is passed as the first argument, catch yields it as the parameter of the block.

Example
catch(1) {|x| x + 2 }       # => 3

When no tag is given, catch yields a new unique object (as from Object.new) as the block parameter. This object can then be used as the argument to throw, and will match the correct catch block.

Example
catch do |obj_A|
  catch do |obj_B|
    throw(obj_B, 123)
    puts "This puts is not reached"
  end

  puts "This puts is displayed"
  456
end

# => 456

catch do |obj_A|
  catch do |obj_B|
    throw(obj_A, 123)
    puts "This puts is still not reached"
  end

  puts "Now this puts is also not reached"
  456
end

# => 123

Transfers control to the end of the active catch block waiting for tag. Raises UncaughtThrowError if there is no catch block for the tag. The optional second parameter supplies a return value for the catch block, which otherwise defaults to nil. For examples, see Kernel::catch.

With a block given, returns an array of two arrays:

Examples:

Example
p = (1..4).partition {|i| i.even? }
p # => [[2, 4], [1, 3]]
p = ('a'..'d').partition {|c| c < 'c' }
p # => [["a", "b"], ["c", "d"]]
h = {foo: 0, bar: 1, baz: 2, bat: 3}
p = h.partition {|key, value| key.start_with?('b') }
p # => [[[:bar, 1], [:baz, 2], [:bat, 3]], [[:foo, 0]]]
p = h.partition {|key, value| value < 2 }
p # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]]]

With no block given, returns an Enumerator.

Related: Enumerable#group_by.

Returns whether for any element object == element:

Example
(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 array of all non-nil elements:

Example
a = [nil, 0, nil, 'a', false, nil, false, nil, 'a', nil, 0, nil]
a.compact # => [0, "a", false, false, "a", 0]

Returns a list of the supported category symbols.

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 the state of the coverage measurement.

Provides a convenient Ruby iterator which executes a block for each entry in the /etc/passwd file.

The code block is passed an Passwd struct.

See ::getpwent above for details.

Example:

Example
require 'etc'

Etc.passwd {|u|
  puts u.name + " = " + u.gecos
}

Returns the Ruby objects created by parsing the given source.

Argument source contains the String to be parsed.

Argument opts, if given, contains a Hash of options for the parsing. See Parsing Options.


When source is a JSON array, returns a Ruby Array:

Example
source = '["foo", 1.0, true, false, null]'
ruby = JSON.parse(source)
ruby # => ["foo", 1.0, true, false, nil]
ruby.class # => Array

When source is a JSON object, returns a Ruby Hash:

Example
source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
ruby = JSON.parse(source)
ruby # => {"a"=>"foo", "b"=>1.0, "c"=>true, "d"=>false, "e"=>nil}
ruby.class # => Hash

For examples of parsing for all JSON data types, see Parsing JSON.

Parses nested JSON objects:

Example
source = <<~JSON
  {
  "name": "Dave",
    "age" :40,
    "hats": [
      "Cattleman's",
      "Panama",
      "Tophat"
    ]
  }
JSON
ruby = JSON.parse(source)
ruby # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}

Raises an exception if source is not valid JSON:

Example
# Raises JSON::ParserError (783: unexpected token at ''):
JSON.parse('')

Calls

Example
parse(source, opts)

with source and possibly modified opts.

Differences from JSON.parse:

Returns a String containing the generated JSON data.

See also JSON.fast_generate, JSON.pretty_generate.

Argument obj is the Ruby object to be converted to JSON.

Argument opts, if given, contains a Hash of options for the generation. See Generating Options.


When obj is an Array, returns a String containing a JSON array:

Example
obj = ["foo", 1.0, true, false, nil]
json = JSON.generate(obj)
json # => '["foo",1.0,true,false,null]'

When obj is a Hash, returns a String containing a JSON object:

Example
obj = {foo: 0, bar: 's', baz: :bat}
json = JSON.generate(obj)
json # => '{"foo":0,"bar":"s","baz":"bat"}'

For examples of generating from other Ruby objects, see Generating JSON from Other Objects.


Raises an exception if any formatting option is not a String.

Raises an exception if obj contains circular references:

Example
a = []; b = []; a.push(b); b.push(a)
# Raises JSON::NestingError (nesting of 100 is too deep):
JSON.generate(a)

Parse a YAML string in yaml. Returns the Psych::Nodes::Document. filename is used in the exception message if a Psych::SyntaxError is raised.

Raises a Psych::SyntaxError when a YAML syntax error is detected.

Example:

Example
Psych.parse("---\n - a\n - b") # => #<Psych::Nodes::Document:0x00>

begin
  Psych.parse("--- `", filename: "file.txt")
rescue Psych::SyntaxError => ex
  ex.file    # => 'file.txt'
  ex.message # => "(file.txt): found character that cannot start any token"
end

See Psych::Nodes for more information about YAML AST.

Search took: 5ms  ·  Total Results: 2303