Parses environment variable env
or its uppercase with splitting like a shell.
env
defaults to the basename of the program.
Defines a new Data class.
measure = Data.define(:amount, :unit) #=> #<Class:0x00007f70c6868498> measure.new(1, 'km') #=> #<data amount=1, unit="km"> # It you store the new class in the constant, it will # affect #inspect and will be more natural to use: Measure = Data.define(:amount, :unit) #=> Measure Measure.new(1, 'km') #=> #<data Measure amount=1, unit="km">
Note that member-less Data is acceptable and might be a useful technique for defining several homogenous data classes, like
class HTTPFetcher Response = Data.define(:body) NotFound = Data.define # ... implementation end
Now, different kinds of responses from HTTPFetcher
would have consistent representation:
#<data HTTPFetcher::Response body="<html..."> #<data HTTPFetcher::NotFound>
And are convenient to use in pattern matching:
case fetcher.get(url) in HTTPFetcher::Response(body) # process body variable in HTTPFetcher::NotFound # handle not found case end
Returns a string representation of self
:
Measure = Data.define(:amount, :unit) distance = Measure[10, 'km'] p distance # uses #inspect underneath #<data Measure amount=10, unit="km"> puts distance # uses #to_s underneath, same representation #<data Measure amount=10, unit="km">
Returns the offset (in characters) of the beginning of the specified match.
When non-negative integer argument n
is given, returns the offset of the beginning of the n
th match:
m = /(.)(.)(\d+)(\d)/.match("THX1138.") # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8"> m[0] # => "HX1138" m.begin(0) # => 1 m[3] # => "113" m.begin(3) # => 3 m = /(т)(е)(с)/.match('тест') # => #<MatchData "тес" 1:"т" 2:"е" 3:"с"> m[0] # => "тес" m.begin(0) # => 0 m[3] # => "с" m.begin(3) # => 2
When string or symbol argument name
is given, returns the offset of the beginning for the named match:
m = /(?<foo>.)(.)(?<bar>.)/.match("hoge") # => #<MatchData "hog" foo:"h" bar:"g"> m[:foo] # => "h" m.begin('foo') # => 0 m[:bar] # => "g" m.begin(:bar) # => 2
Related: MatchData#end
, MatchData#offset
, MatchData#byteoffset
.
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"
Returns a string representation of self
:
m = /.$/.match("foo") # => #<MatchData "o"> m.inspect # => "#<MatchData \"o\">" m = /(.)(.)(.)/.match("foo") # => #<MatchData "foo" 1:"f" 2:"o" 3:"o"> m.inspect # => "#<MatchData \"foo\" 1:\"f\" 2:\"o\ m = /(.)(.)?(.)/.match("fo") # => #<MatchData "fo" 1:"f" 2:nil 3:"o"> m.inspect # => "#<MatchData \"fo\" 1:\"f\" 2:nil 3:\"o\">"
Related: MatchData#to_s
.
Returns the target string if it was frozen; otherwise, returns a frozen copy of the target string:
m = /(.)(.)(\d+)(\d)/.match("THX1138.") # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8"> m.string # => "THX1138."
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
Returns the BigDecimal converted from value
with a precision of ndigits
decimal digits.
When ndigits
is less than the number of significant digits in the value, the result is rounded to that number of digits, according to the current rounding mode; see BigDecimal.mode
.
When ndigits
is 0, the number of digits to correctly represent a float number is determined automatically.
Returns value
converted to a BigDecimal, depending on the type of value
:
Integer
, Float
, Rational
, Complex
, or BigDecimal: converted directly:
# Integer, Complex, or BigDecimal value does not require ndigits; ignored if given. BigDecimal(2) # => 0.2e1 BigDecimal(Complex(2, 0)) # => 0.2e1 BigDecimal(BigDecimal(2)) # => 0.2e1 # Float or Rational value requires ndigits. BigDecimal(2.0, 0) # => 0.2e1 BigDecimal(Rational(2, 1), 0) # => 0.2e1
String: converted by parsing if it contains an integer or floating-point literal; leading and trailing whitespace is ignored:
# String does not require ndigits; ignored if given. BigDecimal('2') # => 0.2e1 BigDecimal('2.0') # => 0.2e1 BigDecimal('0.2e1') # => 0.2e1 BigDecimal(' 2.0 ') # => 0.2e1
Other type that responds to method :to_str
: first converted to a string, then converted to a BigDecimal, as above.
Other type:
Raises an exception if keyword argument exception
is true
.
Returns nil
if keyword argument exception
is false
.
Raises an exception if value
evaluates to a Float
and digits
is larger than Float::DIG + 1.
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 $_.