This is a convenience method which is same as follows:
begin q = PrettyPrint.new(output, maxwidth, newline, &genspace) ... q.flush output end
Creates a file in the underlying file system; returns a new File object based on that file.
With no block given and no arguments, creates and returns file whose:
Directory is the system temporary directory (system-dependent).
Generated filename is unique in that directory.
Permissions are 0600
; see File Permissions.
Mode is 'w+'
(read/write mode, positioned at the end).
With no block, the file is not removed automatically, and so should be explicitly removed.
Example:
f = Tempfile.create # => #<File:/tmp/20220505-9795-17ky6f6> f.class # => File f.path # => "/tmp/20220505-9795-17ky6f6" f.stat.mode.to_s(8) # => "100600" File.exist?(f.path) # => true File.unlink(f.path) File.exist?(f.path) # => false
Argument basename
, if given, may be one of:
A string: the generated filename begins with basename
:
Tempfile.create('foo') # => #<File:/tmp/foo20220505-9795-1gok8l9>
An array of two strings [prefix, suffix]
: the generated filename begins with prefix
and ends with suffix
:
Tempfile.create(%w/foo .jpg/) # => #<File:/tmp/foo20220505-17839-tnjchh.jpg>
With arguments basename
and tmpdir
, the file is created in directory tmpdir
:
Tempfile.create('foo', '.') # => #<File:./foo20220505-9795-1emu6g8>
Keyword arguments mode
and options
are passed directly to method File.open
:
The value given with mode
must be an integer, and may be expressed as the logical OR of constants defined in File::Constants
.
For options
, see Open Options.
With a block given, creates the file as above, passes it to the block, and returns the block’s value; before the return, the file object is closed and the underlying file is removed:
Tempfile.create {|file| file.path } # => "/tmp/20220505-9795-rkists"
Related: Tempfile.new
.
Returns true
if a Proc
object is lambda. false
if non-lambda.
The lambda-ness affects argument handling and the behavior of return
and break
.
A Proc
object generated by proc
ignores extra arguments.
proc {|a,b| [a,b] }.call(1,2,3) #=> [1,2]
It provides nil
for missing arguments.
proc {|a,b| [a,b] }.call(1) #=> [1,nil]
It expands a single array argument.
proc {|a,b| [a,b] }.call([1,2]) #=> [1,2]
A Proc
object generated by lambda
doesn’t have such tricks.
lambda {|a,b| [a,b] }.call(1,2,3) #=> ArgumentError lambda {|a,b| [a,b] }.call(1) #=> ArgumentError lambda {|a,b| [a,b] }.call([1,2]) #=> ArgumentError
Proc#lambda?
is a predicate for the tricks. It returns true
if no tricks apply.
lambda {}.lambda? #=> true proc {}.lambda? #=> false
Proc.new
is the same as proc
.
Proc.new {}.lambda? #=> false
lambda
, proc
and Proc.new
preserve the tricks of a Proc
object given by &
argument.
lambda(&lambda {}).lambda? #=> true proc(&lambda {}).lambda? #=> true Proc.new(&lambda {}).lambda? #=> true lambda(&proc {}).lambda? #=> false proc(&proc {}).lambda? #=> false Proc.new(&proc {}).lambda? #=> false
A Proc
object generated by &
argument has the tricks
def n(&b) b.lambda? end n {} #=> false
The &
argument preserves the tricks if a Proc
object is given by &
argument.
n(&lambda {}) #=> true n(&proc {}) #=> false n(&Proc.new {}) #=> false
A Proc
object converted from a method has no tricks.
def m() end method(:m).to_proc.lambda? #=> true n(&method(:m)) #=> true n(&method(:m).to_proc) #=> true
define_method
is treated the same as method definition. The defined method has no tricks.
class C define_method(:d) {} end C.new.d(1,2) #=> ArgumentError C.new.method(:d).to_proc.lambda? #=> true
define_method
always defines a method without the tricks, even if a non-lambda Proc
object is given. This is the only exception for which the tricks are not preserved.
class C define_method(:e, &proc {}) end C.new.e(1,2) #=> ArgumentError C.new.method(:e).to_proc.lambda? #=> true
This exception ensures that methods never have tricks and makes it easy to have wrappers to define methods that behave as usual.
class C def self.def2(name, &body) define_method(name, &body) end def2(:f) {} end C.new.f(1,2) #=> ArgumentError
The wrapper def2 defines a method which has no tricks.
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.
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"
Returns internal information of TracePoint
.
The contents of the returned value are implementation specific. It may be changed in future.
This method is only for debugging TracePoint
itself.
Activates the trace.
Returns true
if trace was enabled. Returns false
if trace was disabled.
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 call. If target and target_line are both nil, then target_thread will default to the current thread if a block is given.
trace.enabled? #=> false trace.enable do trace.enabled? # only enabled for this block and thread end trace.enabled? #=> false
target
, target_line
and target_thread
parameters are used to limit tracing only to specified code objects. target
should be a code object for which RubyVM::InstructionSequence.of
will return an instruction sequence.
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.
trace.enable { p tp.lineno } #=> RuntimeError: access from outside
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.
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.
-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.
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.
-20.clamp(0..) #=> 0 523.clamp(..100) #=> 100
When range.end is excluded and not nil
, an exception is raised.
100.clamp(0...100) # ArgumentError
Yields self to the block and returns the result of the block.
3.next.then {|x| x**x }.to_s #=> "256"
Good usage for then
is value piping in method chains:
require 'open-uri' require 'json' construct_url(arguments). then {|url| URI(url).read }. then {|response| JSON.parse(response) }
When called without block, the method returns Enumerator
, which can be used, for example, for conditional circuit-breaking:
# meets condition, no-op 1.then.detect(&:odd?) # => 1 # does not meet condition, drop value 2.then.detect(&:odd?) # => nil
Good usage for then
is value piping in method chains:
require 'open-uri' require 'json' construct_url(arguments). then {|url| URI(url).read }. then {|response| JSON.parse(response) }
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 a ArgumentError
. Converting nil
generates a TypeError
. Exceptions can be suppressed by passing exception: false
.
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:
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 the process ID (pid) of the new process, without waiting for it to complete.
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 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:
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:
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:
spawn('echo "Foo"') # => 799031 Process.wait # => 799031
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 to be called, and the string to be used as the name of the executing process.
spawn('/usr/bin/date') # Path to date on Unix-style system. Process.wait
Output:
Mon Aug 28 11:43:10 AM CDT 2023
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:
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.
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
).
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.
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.
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:
The first having those elements for which the block returns a truthy value.
The other having all other elements.
Examples:
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
:
(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:
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:
require 'etc' Etc.passwd {|u| puts u.name + " = " + u.gecos }