Returns a shallow copy of self
— the instance variables of self
are copied, but not the objects they reference.
If the method is supplied any keyword arguments, the copy will be created with the respective field values updated to use the supplied keyword argument values. Note that it is an error to supply a keyword that the Data
class does not have as a member.
Point = Data.define(:x, :y) origin = Point.new(x: 0, y: 0) up = origin.with(x: 1) right = origin.with(y: 1) up_and_right = up.with(y: 1) p origin # #<data Point x=0, y=0> p up # #<data Point x=1, y=0> p right # #<data Point x=0, y=1> p up_and_right # #<data Point x=1, y=1> out = origin.with(z: 1) # ArgumentError: unknown keyword: :z some_point = origin.with(1, 2) # ArgumentError: expected keyword arguments, got positional arguments
Returns size of the match array:
m = /(.)(.)(\d+)(\d)/.match("THX1138.") # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8"> m.size # => 5
MatchData#length
is an alias for MatchData.size
.
Returns the matched substring corresponding to the given argument.
When non-negative argument n
is given, returns the matched substring for the n
th match:
m = /(.)(.)(\d+)(\d)(\w)?/.match("THX1138.") # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8" 5:nil> m.match(0) # => "HX1138" m.match(4) # => "8" m.match(5) # => nil
When string or symbol argument name
is given, returns the matched substring for the given name:
m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge") # => #<MatchData "hoge" foo:"h" bar:"ge"> m.match('foo') # => "h" m.match(:bar) # => "ge"
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'
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
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.
Kernel#format
is an alias for Kernel#sprintf
.
Equivalent to Proc.new
, except the resulting Proc
objects check the number of parameters passed when called.
spawn executes specified command and return its pid.
pid = spawn("tar xf ruby-2.0.0-p195.tar.bz2") Process.wait pid pid = spawn(RbConfig.ruby, "-eputs'Hello, world!'") Process.wait pid
This method is similar to Kernel#system
but it doesn’t wait for the command to finish.
The parent process should use Process.wait
to collect the termination status of its child or use Process.detach
to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.
spawn has bunch of options to specify process attributes:
env: hash name => val : set the environment variable name => nil : unset the environment variable the keys and the values except for +nil+ must be strings. command...: commandline : command line string which is passed to the standard shell cmdname, arg1, ... : command name and one or more arguments (This form does not use the shell. See below for caveats.) [cmdname, argv0], arg1, ... : command name, argv[0] and zero or more arguments (no shell) options: hash clearing environment variables: :unsetenv_others => true : clear environment variables except specified by env :unsetenv_others => false : don't clear (default) process group: :pgroup => true or 0 : make a new process group :pgroup => pgid : join the specified process group :pgroup => nil : don't change the process group (default) create new process group: Windows only :new_pgroup => true : the new process is the root process of a new process group :new_pgroup => false : don't create a new process group (default) resource limit: resourcename is core, cpu, data, etc. See Process.setrlimit. :rlimit_resourcename => limit :rlimit_resourcename => [cur_limit, max_limit] umask: :umask => int redirection: key: FD : single file descriptor in child process [FD, FD, ...] : multiple file descriptor in child process value: FD : redirect to the file descriptor in parent process string : redirect to file with open(string, "r" or "w") [string] : redirect to file with open(string, File::RDONLY) [string, open_mode] : redirect to file with open(string, open_mode, 0644) [string, open_mode, perm] : redirect to file with open(string, open_mode, perm) [:child, FD] : redirect to the redirected file descriptor :close : close the file descriptor in child process FD is one of follows :in : the file descriptor 0 which is the standard input :out : the file descriptor 1 which is the standard output :err : the file descriptor 2 which is the standard error integer : the file descriptor of specified the integer io : the file descriptor specified as io.fileno file descriptor inheritance: close non-redirected non-standard fds (3, 4, 5, ...) or not :close_others => false : inherit current directory: :chdir => str
The cmdname, arg1, ...
form does not use the shell. However, on different OSes, different things are provided as built-in commands. An example of this is +‘echo’+, which is a built-in on Windows, but is a normal program on Linux and Mac OS X. This means that Process.spawn 'echo', '%Path%'
will display the contents of the %Path%
environment variable on Windows, but Process.spawn 'echo', '$PATH'
prints the literal $PATH
.
If a hash is given as env
, the environment is updated by env
before exec(2)
in the child process. If a pair in env
has nil as the value, the variable is deleted.
# set FOO as BAR and unset BAZ. pid = spawn({"FOO"=>"BAR", "BAZ"=>nil}, command)
If a hash is given as options
, it specifies process group, create new process group, resource limit, current directory, umask and redirects for the child process. Also, it can be specified to clear environment variables.
The :unsetenv_others
key in options
specifies to clear environment variables, other than specified by env
.
pid = spawn(command, :unsetenv_others=>true) # no environment variable pid = spawn({"FOO"=>"BAR"}, command, :unsetenv_others=>true) # FOO only
The :pgroup
key in options
specifies a process group. The corresponding value should be true, zero, a positive integer, or nil. true and zero cause the process to be a process leader of a new process group. A non-zero positive integer causes the process to join the provided process group. The default value, nil, causes the process to remain in the same process group.
pid = spawn(command, :pgroup=>true) # process leader pid = spawn(command, :pgroup=>10) # belongs to the process group 10
The :new_pgroup
key in options
specifies to pass CREATE_NEW_PROCESS_GROUP
flag to CreateProcessW()
that is Windows API. This option is only for Windows. true means the new process is the root process of the new process group. The new process has CTRL+C disabled. This flag is necessary for Process.kill(:SIGINT, pid)
on the subprocess. :new_pgroup is false by default.
pid = spawn(command, :new_pgroup=>true) # new process group pid = spawn(command, :new_pgroup=>false) # same process group
The :rlimit_
foo key specifies a resource limit. foo should be one of resource types such as core
. The corresponding value should be an integer or an array which have one or two integers: same as cur_limit and max_limit arguments for Process.setrlimit
.
cur, max = Process.getrlimit(:CORE) pid = spawn(command, :rlimit_core=>[0,max]) # disable core temporary. pid = spawn(command, :rlimit_core=>max) # enable core dump pid = spawn(command, :rlimit_core=>0) # never dump core.
The :umask
key in options
specifies the umask.
pid = spawn(command, :umask=>077)
The :in, :out, :err, an integer, an IO
and an array key specifies a redirection. The redirection maps a file descriptor in the child process.
For example, stderr can be merged into stdout as follows:
pid = spawn(command, :err=>:out) pid = spawn(command, 2=>1) pid = spawn(command, STDERR=>:out) pid = spawn(command, STDERR=>STDOUT)
The hash keys specifies a file descriptor in the child process started by spawn
. :err, 2 and STDERR specifies the standard error stream (stderr).
The hash values specifies a file descriptor in the parent process which invokes spawn
. :out, 1 and STDOUT specifies the standard output stream (stdout).
In the above example, the standard output in the child process is not specified. So it is inherited from the parent process.
The standard input stream (stdin) can be specified by :in, 0 and STDIN.
A filename can be specified as a hash value.
pid = spawn(command, :in=>"/dev/null") # read mode pid = spawn(command, :out=>"/dev/null") # write mode pid = spawn(command, :err=>"log") # write mode pid = spawn(command, [:out, :err]=>"/dev/null") # write mode pid = spawn(command, 3=>"/dev/null") # read mode
For stdout and stderr (and combination of them), it is opened in write mode. Otherwise read mode is used.
For specifying flags and permission of file creation explicitly, an array is used instead.
pid = spawn(command, :in=>["file"]) # read mode is assumed pid = spawn(command, :in=>["file", "r"]) pid = spawn(command, :out=>["log", "w"]) # 0644 assumed pid = spawn(command, :out=>["log", "w", 0600]) pid = spawn(command, :out=>["log", File::WRONLY|File::EXCL|File::CREAT, 0600])
The array specifies a filename, flags and permission. The flags can be a string or an integer. If the flags is omitted or nil, File::RDONLY is assumed. The permission should be an integer. If the permission is omitted or nil, 0644 is assumed.
If an array of IOs and integers are specified as a hash key, all the elements are redirected.
# stdout and stderr is redirected to log file. # The file "log" is opened just once. pid = spawn(command, [:out, :err]=>["log", "w"])
Another way to merge multiple file descriptors is [:child, fd]. [:child, fd] means the file descriptor in the child process. This is different from fd. For example, :err=>:out means redirecting child stderr to parent stdout. But :err=>[:child, :out] means redirecting child stderr to child stdout. They differ if stdout is redirected in the child process as follows.
# stdout and stderr is redirected to log file. # The file "log" is opened just once. pid = spawn(command, :out=>["log", "w"], :err=>[:child, :out])
[:child, :out] can be used to merge stderr into stdout in IO.popen
. In this case, IO.popen
redirects stdout to a pipe in the child process and [:child, :out] refers the redirected stdout.
io = IO.popen(["sh", "-c", "echo out; echo err >&2", :err=>[:child, :out]]) p io.read #=> "out\nerr\n"
The :chdir
key in options
specifies the current directory.
pid = spawn(command, :chdir=>"/var/tmp")
spawn closes all non-standard unspecified descriptors by default. The “standard” descriptors are 0, 1 and 2. This behavior is specified by :close_others option. :close_others doesn’t affect the standard descriptors which are closed only if :close is specified explicitly.
pid = spawn(command, :close_others=>true) # close 3,4,5,... (default) pid = spawn(command, :close_others=>false) # don't close 3,4,5,...
:close_others is false by default for spawn and IO.popen
.
Note that fds which close-on-exec flag is already set are closed regardless of :close_others option.
So IO.pipe
and spawn can be used as IO.popen
.
# similar to r = IO.popen(command) r, w = IO.pipe pid = spawn(command, :out=>w) # r, w is closed in the child process. w.close
:close is specified as a hash value to close a fd individually.
f = open(foo) system(command, f=>:close) # don't inherit f.
If a file descriptor need to be inherited, io=>io can be used.
# valgrind has --log-fd option for log destination. # log_w=>log_w indicates log_w.fileno inherits to child process. log_r, log_w = IO.pipe pid = spawn("valgrind", "--log-fd=#{log_w.fileno}", "echo", "a", log_w=>log_w) log_w.close p log_r.read
It is also possible to exchange file descriptors.
pid = spawn(command, :out=>:err, :err=>:out)
The hash keys specify file descriptors in the child process. The hash values specifies file descriptors in the parent process. So the above specifies exchanging stdout and stderr. Internally, spawn
uses an extra file descriptor to resolve such cyclic file descriptor mapping.
See Kernel.exec
for the standard shell.
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
Enumerable#member?
is an alias for Enumerable#include?
.
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]
Computes the arctangent of decimal
to the specified number of digits of precision, numeric
.
If decimal
is NaN, returns NaN.
BigMath.atan(BigDecimal('-1'), 16).to_s #=> "-0.785398163397448309615660845819878471907514682065e0"