This is a convenience method which is same as follows:
begin q = PrettyPrint.new(output, maxwidth, newline, &genspace) ... q.flush output end
Exits the current transaction block, committing any changes specified in the transaction block.
Raises an exception if called outside a transaction block.
Unlinks (deletes) the file from the filesystem. One should always unlink the file after using it, as is explained in the “Explicit close” good practice section in the Tempfile
overview:
file = Tempfile.new('foo') begin # ...do something with file... ensure file.close file.unlink # deletes the temp file end
On POSIX systems it’s possible to unlink a file before closing it. This practice is explained in detail in the Tempfile
overview (section “Unlink after creation”); please refer there for more information.
However, unlink-before-close may not be supported on non-POSIX operating systems. Microsoft Windows is the most notable case: unlinking a non-closed file will result in an error, which this method will silently ignore. If you want to practice unlink-before-close whenever possible, then you should write code like this:
file = Tempfile.new('foo') file.unlink # On Windows this silently fails. begin # ... do something with file ... ensure file.close! # Closes the file handle. If the file wasn't unlinked # because #unlink failed, then this method will attempt # to do so again. end
The string representation of false
is “false”.
Returns the unique identifier for this proc, along with an indication of where the proc was defined.
Returns a human-readable description of the underlying method.
"cat".method(:count).inspect #=> "#<Method: String#count(*)>" (1..3).method(:map).inspect #=> "#<Method: Range(Enumerable)#map()>"
In the latter case, the method description includes the “owner” of the original method (Enumerable
module, which is included into Range
).
inspect
also provides, when possible, method argument names (call sequence) and source location.
require 'net/http' Net::HTTP.method(:get).inspect #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
...
in argument definition means argument is optional (has some default value).
For methods defined in C (language core and extensions), location and argument names can’t be extracted, and only generic information is provided in form of *
(any number of arguments) or _
(some positional argument).
"cat".method(:count).inspect #=> "#<Method: String#count(*)>" "cat".method(:+).inspect #=> "#<Method: String#+(_)>""
Dissociates meth from its current receiver. The resulting UnboundMethod
can subsequently be bound to a new object of the same class (see UnboundMethod
).
Returns a human-readable description of the underlying method.
"cat".method(:count).inspect #=> "#<Method: String#count(*)>" (1..3).method(:map).inspect #=> "#<Method: Range(Enumerable)#map()>"
In the latter case, the method description includes the “owner” of the original method (Enumerable
module, which is included into Range
).
inspect
also provides, when possible, method argument names (call sequence) and source location.
require 'net/http' Net::HTTP.method(:get).inspect #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
...
in argument definition means argument is optional (has some default value).
For methods defined in C (language core and extensions), location and argument names can’t be extracted, and only generic information is provided in form of *
(any number of arguments) or _
(some positional argument).
"cat".method(:count).inspect #=> "#<Method: String#count(*)>" "cat".method(:+).inspect #=> "#<Method: String#+(_)>""
Bind umeth to obj. If Klass was the class from which umeth was obtained, obj.kind_of?(Klass)
must be true.
class A def test puts "In test, class = #{self.class}" end end class B < A end class C < B end um = B.instance_method(:test) bm = um.bind(C.new) bm.call bm = um.bind(B.new) bm.call bm = um.bind(A.new) bm.call
produces:
In test, class = C In test, class = B prog.rb:16:in `bind': bind argument must be an instance of B (TypeError) from prog.rb:16
The calling thread will suspend execution and run this thr
.
Does not return until thr
exits or until the given limit
seconds have passed.
If the time limit expires, nil
will be returned, otherwise thr
is returned.
Any threads not joined will be killed when the main program exits.
If thr
had previously raised an exception and the ::abort_on_exception
or $DEBUG flags are not set, (so the exception has not yet been processed), it will be processed at this time.
a = Thread.new { print "a"; sleep(10); print "b"; print "c" } x = Thread.new { print "x"; Thread.pass; print "y"; print "z" } x.join # Let thread x finish, thread a will be killed on exit. #=> "axyz"
The following example illustrates the limit
parameter.
y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }} puts "Waiting" until y.join(0.15)
This will produce:
tick... Waiting tick... Waiting tick... tick...
Dump the name, id, and status of thr to a string.
Return a string containing a human-readable TracePoint
status.
Line number of the event
Equivalent to:
io.write(sprintf(format_string, *objects))
For details on format_string
, see Format Specifications.
With the single argument format_string
, formats objects
into the string, then writes the formatted string to $stdout:
printf('%4.4d %10s %2.2f', 24, 24, 24.0)
Output (on $stdout):
0024 24 24.00#
With arguments io
and format_string
, formats objects
into the string, then writes the formatted string to io
:
printf($stderr, '%4.4d %10s %2.2f', 24, 24, 24.0)
Output (on $stderr):
0024 24 24.00# => nil
With no arguments, does nothing.
Equivalent to $stdout.print(*objects)
, this method is the straightforward way to write to $stdout
.
Writes the given objects to $stdout
; returns nil
. Appends the output record separator $OUTPUT_RECORD_SEPARATOR
$\
), if it is not nil
.
With argument objects
given, for each object:
Converts via its method to_s
if not a string.
Writes to stdout
.
If not the last object, writes the output field separator $OUTPUT_FIELD_SEPARATOR
($,
if it is not nil
.
With default separators:
objects = [0, 0.0, Rational(0, 1), Complex(0, 0), :zero, 'zero'] $OUTPUT_RECORD_SEPARATOR $OUTPUT_FIELD_SEPARATOR print(*objects)
Output:
nil nil 00.00/10+0izerozero
With specified separators:
$OUTPUT_RECORD_SEPARATOR = "\n" $OUTPUT_FIELD_SEPARATOR = ',' print(*objects)
Output:
0,0.0,0/1,0+0i,zero,zero
With no argument given, writes the content of $_
(which is usually the most recent user input):
gets # Sets $_ to the most recent user input. print # Prints $_.
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.
Returns an integer converted from object
.
Tries to convert object
to an integer using to_int
first and to_i
second; see below for exceptions.
With a non-zero base
, object
must be a string or convertible to a string.
With integer argument object
given, returns object
:
Integer(1) # => 1 Integer(-1) # => -1
With floating-point argument object
given, returns object
truncated to an integer:
Integer(1.9) # => 1 # Rounds toward zero. Integer(-1.9) # => -1 # Rounds toward zero.
With string argument object
and zero base
given, returns object
converted to an integer in base 10:
Integer('100') # => 100 Integer('-100') # => -100
With base
zero, string object
may contain leading characters to specify the actual base (radix indicator):
Integer('0100') # => 64 # Leading '0' specifies base 8. Integer('0b100') # => 4 # Leading '0b', specifies base 2. Integer('0x100') # => 256 # Leading '0x' specifies base 16.
With a positive base
(in range 2..36) given, returns object
converted to an integer in the given base:
Integer('100', 2) # => 4 Integer('100', 8) # => 64 Integer('-100', 16) # => -256
With a negative base
(in range -36..-2) given, returns object
converted to an integer in the radix indicator if exists or -base
:
Integer('0x100', -2) # => 256 Integer('100', -2) # => 4 Integer('0b100', -8) # => 4 Integer('100', -8) # => 64 Integer('0o100', -10) # => 64 Integer('100', -10) # => 100
base
-1 is equal the -10 case.
When converting strings, surrounding whitespace and embedded underscores are allowed and ignored:
Integer(' 100 ') # => 100 Integer('-1_0_0', 16) # => -256
Examples with object
of various other classes:
Integer(Rational(9, 10)) # => 0 # Rounds toward zero. Integer(Complex(2, 0)) # => 2 # Imaginary part must be zero. Integer(Time.now) # => 1650974042
With optional keyword argument exception
given as true
(the default):
Raises TypeError
if object
does not respond to to_int
or to_i
.
Raises TypeError
if object
is nil
.
Raise ArgumentError
if object
is an invalid string.
With exception
given as false
, an exception of any kind is suppressed and nil
is returned.
Returns the string resulting from formatting objects
into format_string
.
For details on format_string
, see Format Specifications.
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.
Returns the first element for which the block returns a truthy value.
With a block given, calls the block with successive elements of the collection; returns the first element for which the block returns a truthy value:
(0..9).find {|element| element > 2} # => 3
If no such element is found, calls if_none_proc
and returns its return value.
(0..9).find(proc {false}) {|element| element > 12} # => false {foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?('b') } # => [:bar, 1] {foo: 0, bar: 1, baz: 2}.find(proc {[]}) {|key, value| key.start_with?('c') } # => []
With no block given, returns an Enumerator
.
Returns an array of objects returned by the block.
With a block given, calls the block with successive elements; returns an array of the objects returned by the block:
(0..4).map {|i| i*i } # => [0, 1, 4, 9, 16] {foo: 0, bar: 1, baz: 2}.map {|key, value| value*2} # => [0, 2, 4]
With no block given, returns an Enumerator
.