Returns the element at offset index
.
With the single Integer argument index
, returns the element at offset index
:
a = [:foo, 'bar', 2] a.fetch(1) # => "bar"
If index
is negative, counts from the end of the array:
a = [:foo, 'bar', 2] a.fetch(-1) # => 2 a.fetch(-2) # => "bar"
With arguments index
and default_value
, returns the element at offset index
if index is in range, otherwise returns default_value
:
a = [:foo, 'bar', 2] a.fetch(1, nil) # => "bar"
With argument index
and a block, returns the element at offset index
if index is in range (and the block is not called); otherwise calls the block with index and returns its return value:
a = [:foo, 'bar', 2] a.fetch(1) {|index| raise 'Cannot happen' } # => "bar" a.fetch(50) {|index| "Value for #{index}" } # => "Value for 50"
Returns a new 2-element Array containing the minimum and maximum values from self
, either per method <=>
or per a given block:.
When no block is given, each element in self
must respond to method <=>
with an Integer; returns a new 2-element Array containing the minimum and maximum values from self
, per method <=>
:
[0, 1, 2].minmax # => [0, 2]
When a block is given, the block must return an Integer; the block is called self.size-1
times to compare elements; returns a new 2-element Array containing the minimum and maximum values from self
, per the block:
['0', '00', '000'].minmax {|a, b| a.size <=> b.size } # => ["0", "000"]
Returns a hash of parsed elements.
Raise an ArgumentError
when the string length is longer than limit. You can stop this check by passing ‘limit: nil`, but note that it may take a long time to parse.
Creates a new Date
object by parsing from a string according to some typical XML Schema formats.
Date.xmlschema('2001-02-03') #=> #<Date: 2001-02-03 ...>
Raise an ArgumentError
when the string length is longer than limit. You can stop this check by passing ‘limit: nil`, but note that it may take a long time to parse.
This method is equivalent to strftime(‘%F’).
Creates a new DateTime
object by parsing from a string according to some typical XML Schema formats.
DateTime.xmlschema('2001-02-03T04:05:06+07:00') #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
Raise an ArgumentError
when the string length is longer than limit. You can stop this check by passing ‘limit: nil`, but note that it may take a long time to parse.
This method is equivalent to strftime(‘%FT%T%:z’). The optional argument n
is the number of digits for fractional seconds.
DateTime.parse('2001-02-03T04:05:06.123456789+07:00').iso8601(9) #=> "2001-02-03T04:05:06.123456789+07:00"
Parses time
as a dateTime defined by the XML Schema and converts it to a Time
object. The format is a restricted version of the format defined by ISO 8601.
ArgumentError
is raised if time
is not compliant with the format or if the Time
class cannot represent the specified time.
See xmlschema
for more information on this format.
require 'time' Time.xmlschema("2011-10-05T22:26:12-04:00") #=> 2011-10-05 22:26:12-04:00
You must require ‘time’ to use this method.
Returns a string which represents the time as a dateTime defined by XML Schema:
CCYY-MM-DDThh:mm:ssTZD CCYY-MM-DDThh:mm:ss.sssTZD
where TZD is Z or [+-]hh:mm.
If self is a UTC time, Z is used as TZD. [+-]hh:mm is used otherwise.
fractional_digits
specifies a number of digits to use for fractional seconds. Its default value is 0.
require 'time' t = Time.now t.iso8601 # => "2011-10-05T22:26:12-04:00"
You must require ‘time’ to use this method.
Return a value from the database by locating the key string provided. If the key is not found, returns ifnone
. If ifnone
is not given, raises IndexError
.
Reads and returns a character in raw mode.
See IO#raw
for details on the parameters.
You must require ‘io/console’ to use this method.
Retrieves the value corresponding to key. If there is no value associated with key, default will be returned instead.
Returns a two element array which contains the minimum and the maximum value in the range.
Can be given an optional block to override the default comparison method a <=> b
.
Scans one character and returns it. This method is multibyte character sensitive.
s = StringScanner.new("ab") s.getch # => "a" s.getch # => "b" s.getch # => nil s = StringScanner.new("\244\242".force_encoding("euc-jp")) s.getch # => "\x{A4A2}" # Japanese hira-kana "A" in EUC-JP s.getch # => nil
Returns the value for the given key
, if found.
h = {foo: 0, bar: 1, baz: 2} h.fetch(:bar) # => 1
If key
is not found and no block was given, returns default_value
:
{}.fetch(:nosuch, :default) # => :default {}.fetch(:nosuch) # => nil
If key
is not found and a block was given, yields key
to the block and returns the block’s return value:
{}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
Raises KeyError
if neither default_value
nor a block was given.
Note that this method does not use the values of either default
or default_proc
.
If name
is the name of an environment variable, returns its value:
ENV['foo'] = '0' ENV.fetch('foo') # => '0'
Otherwise if a block is given (but not a default value), yields name
to the block and returns the block’s return value:
ENV.fetch('foo') { |name| :need_not_return_a_string } # => :need_not_return_a_string
Otherwise if a default value is given (but not a block), returns the default value:
ENV.delete('foo') ENV.fetch('foo', :default_need_not_be_a_string) # => :default_need_not_be_a_string
If the environment variable does not exist and both default and block are given, issues a warning (“warning: block supersedes default value argument”), yields name
to the block, and returns the block’s return value:
ENV.fetch('foo', :default) { |name| :block_return } # => :block_return
Raises KeyError
if name
is valid, but not found, and neither default value nor block is given:
ENV.fetch('foo') # Raises KeyError (key not found: "foo")
Raises an exception if name
is invalid. See Invalid Names and Values.
This is a convenience method which is same as follows:
begin q = PrettyPrint.new(output, maxwidth, newline, &genspace) ... q.flush output end
This method is just like PStore#[]
, save that you may also provide a default value for the object. In the event the specified name is not found in the data store, your default will be returned instead. If you do not specify a default, PStore::Error
will be raised if the object is not found.
WARNING: This method is only valid in a PStore#transaction
. It will raise PStore::Error
if called at any other time.
Returns a fiber-local for the given key. If the key can’t be found, there are several options: With no other arguments, it will raise a KeyError
exception; if default is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned. See Thread#[]
and Hash#fetch
.
Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result.
The syntax of a format sequence is as follows.
%[flags][width][.precision]type
A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf
argument is to be interpreted, while the flags modify that interpretation.
The field type characters are:
Field | Integer Format ------+-------------------------------------------------------------- b | Convert argument as a binary number. | Negative numbers will be displayed as a two's complement | prefixed with `..1'. B | Equivalent to `b', but uses an uppercase 0B for prefix | in the alternative format by #. d | Convert argument as a decimal number. i | Identical to `d'. o | Convert argument as an octal number. | Negative numbers will be displayed as a two's complement | prefixed with `..7'. u | Identical to `d'. x | Convert argument as a hexadecimal number. | Negative numbers will be displayed as a two's complement | prefixed with `..f' (representing an infinite string of | leading 'ff's). X | Equivalent to `x', but uses uppercase letters. Field | Float Format ------+-------------------------------------------------------------- e | Convert floating point argument into exponential notation | with one digit before the decimal point as [-]d.dddddde[+-]dd. | The precision specifies the number of digits after the decimal | point (defaulting to six). E | Equivalent to `e', but uses an uppercase E to indicate | the exponent. f | Convert floating point argument as [-]ddd.dddddd, | where the precision specifies the number of digits after | the decimal point. g | Convert a floating point number using exponential form | if the exponent is less than -4 or greater than or | equal to the precision, or in dd.dddd form otherwise. | The precision specifies the number of significant digits. G | Equivalent to `g', but use an uppercase `E' in exponent form. a | Convert floating point argument as [-]0xh.hhhhp[+-]dd, | which is consisted from optional sign, "0x", fraction part | as hexadecimal, "p", and exponential part as decimal. A | Equivalent to `a', but use uppercase `X' and `P'. Field | Other Format ------+-------------------------------------------------------------- c | Argument is the numeric code for a single character or | a single character string itself. p | The valuing of argument.inspect. s | Argument is a string to be substituted. If the format | sequence contains a precision, at most that many characters | will be copied. % | A percent sign itself will be displayed. No argument taken.
The flags modifies the behavior of the formats. The flag characters are:
Flag | Applies to | Meaning ---------+---------------+----------------------------------------- space | bBdiouxX | Leave a space at the start of | aAeEfgG | non-negative numbers. | (numeric fmt) | For `o', `x', `X', `b' and `B', use | | a minus sign with absolute value for | | negative values. ---------+---------------+----------------------------------------- (digit)$ | all | Specifies the absolute argument number | | for this field. Absolute and relative | | argument numbers cannot be mixed in a | | sprintf string. ---------+---------------+----------------------------------------- # | bBoxX | Use an alternative format. | aAeEfgG | For the conversions `o', increase the precision | | until the first digit will be `0' if | | it is not formatted as complements. | | For the conversions `x', `X', `b' and `B' | | on non-zero, prefix the result with ``0x'', | | ``0X'', ``0b'' and ``0B'', respectively. | | For `a', `A', `e', `E', `f', `g', and 'G', | | force a decimal point to be added, | | even if no digits follow. | | For `g' and 'G', do not remove trailing zeros. ---------+---------------+----------------------------------------- + | bBdiouxX | Add a leading plus sign to non-negative | aAeEfgG | numbers. | (numeric fmt) | For `o', `x', `X', `b' and `B', use | | a minus sign with absolute value for | | negative values. ---------+---------------+----------------------------------------- - | all | Left-justify the result of this conversion. ---------+---------------+----------------------------------------- 0 (zero) | bBdiouxX | Pad with zeros, not spaces. | aAeEfgG | For `o', `x', `X', `b' and `B', radix-1 | (numeric fmt) | is used for negative numbers formatted as | | complements. ---------+---------------+----------------------------------------- * | all | Use the next argument as the field width. | | If negative, left-justify the result. If the | | asterisk is followed by a number and a dollar | | sign, use the indicated argument as the width.
Examples of flags:
# `+' and space flag specifies the sign of non-negative numbers. sprintf("%d", 123) #=> "123" sprintf("%+d", 123) #=> "+123" sprintf("% d", 123) #=> " 123" # `#' flag for `o' increases number of digits to show `0'. # `+' and space flag changes format of negative numbers. sprintf("%o", 123) #=> "173" sprintf("%#o", 123) #=> "0173" sprintf("%+o", -123) #=> "-173" sprintf("%o", -123) #=> "..7605" sprintf("%#o", -123) #=> "..7605" # `#' flag for `x' add a prefix `0x' for non-zero numbers. # `+' and space flag disables complements for negative numbers. sprintf("%x", 123) #=> "7b" sprintf("%#x", 123) #=> "0x7b" sprintf("%+x", -123) #=> "-7b" sprintf("%x", -123) #=> "..f85" sprintf("%#x", -123) #=> "0x..f85" sprintf("%#x", 0) #=> "0" # `#' for `X' uses the prefix `0X'. sprintf("%X", 123) #=> "7B" sprintf("%#X", 123) #=> "0X7B" # `#' flag for `b' add a prefix `0b' for non-zero numbers. # `+' and space flag disables complements for negative numbers. sprintf("%b", 123) #=> "1111011" sprintf("%#b", 123) #=> "0b1111011" sprintf("%+b", -123) #=> "-1111011" sprintf("%b", -123) #=> "..10000101" sprintf("%#b", -123) #=> "0b..10000101" sprintf("%#b", 0) #=> "0" # `#' for `B' uses the prefix `0B'. sprintf("%B", 123) #=> "1111011" sprintf("%#B", 123) #=> "0B1111011" # `#' for `e' forces to show the decimal point. sprintf("%.0e", 1) #=> "1e+00" sprintf("%#.0e", 1) #=> "1.e+00" # `#' for `f' forces to show the decimal point. sprintf("%.0f", 1234) #=> "1234" sprintf("%#.0f", 1234) #=> "1234." # `#' for `g' forces to show the decimal point. # It also disables stripping lowest zeros. sprintf("%g", 123.4) #=> "123.4" sprintf("%#g", 123.4) #=> "123.400" sprintf("%g", 123456) #=> "123456" sprintf("%#g", 123456) #=> "123456."
The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.
Examples of width:
# padding is done by spaces, width=20 # 0 or radix-1. <------------------> sprintf("%20d", 123) #=> " 123" sprintf("%+20d", 123) #=> " +123" sprintf("%020d", 123) #=> "00000000000000000123" sprintf("%+020d", 123) #=> "+0000000000000000123" sprintf("% 020d", 123) #=> " 0000000000000000123" sprintf("%-20d", 123) #=> "123 " sprintf("%-+20d", 123) #=> "+123 " sprintf("%- 20d", 123) #=> " 123 " sprintf("%020x", -123) #=> "..ffffffffffffffff85"
For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s
will always contribute exactly ten characters to the result.)
Examples of precisions:
# precision for `d', 'o', 'x' and 'b' is # minimum number of digits <------> sprintf("%20.8d", 123) #=> " 00000123" sprintf("%20.8o", 123) #=> " 00000173" sprintf("%20.8x", 123) #=> " 0000007b" sprintf("%20.8b", 123) #=> " 01111011" sprintf("%20.8d", -123) #=> " -00000123" sprintf("%20.8o", -123) #=> " ..777605" sprintf("%20.8x", -123) #=> " ..ffff85" sprintf("%20.8b", -11) #=> " ..110101" # "0x" and "0b" for `#x' and `#b' is not counted for # precision but "0" for `#o' is counted. <------> sprintf("%#20.8d", 123) #=> " 00000123" sprintf("%#20.8o", 123) #=> " 00000173" sprintf("%#20.8x", 123) #=> " 0x0000007b" sprintf("%#20.8b", 123) #=> " 0b01111011" sprintf("%#20.8d", -123) #=> " -00000123" sprintf("%#20.8o", -123) #=> " ..777605" sprintf("%#20.8x", -123) #=> " 0x..ffff85" sprintf("%#20.8b", -11) #=> " 0b..110101" # precision for `e' is number of # digits after the decimal point <------> sprintf("%20.8e", 1234.56789) #=> " 1.23456789e+03" # precision for `f' is number of # digits after the decimal point <------> sprintf("%20.8f", 1234.56789) #=> " 1234.56789000" # precision for `g' is number of # significant digits <-------> sprintf("%20.8g", 1234.56789) #=> " 1234.5679" # <-------> sprintf("%20.8g", 123456789) #=> " 1.2345679e+08" # precision for `s' is # maximum number of characters <------> sprintf("%20.8s", "string test") #=> " string t"
Examples:
sprintf("%d %04x", 123, 123) #=> "123 007b" sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'" sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello" sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8" sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23" sprintf("%u", -123) #=> "-123"
For more complex formatting, Ruby supports a reference by name. %<name>s style uses format style, but %{name} style doesn’t.
Examples:
sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 }) #=> 1 : 2.000000 sprintf("%{foo}f", { :foo => 1 }) # => "1f"
Returns a two element array which contains the minimum and the maximum value in the enumerable. The first form assumes all objects implement <=>
; the second uses the block to return a <=> b.
a = %w(albatross dog horse) a.minmax #=> ["albatross", "horse"] a.minmax { |a, b| a.length <=> b.length } #=> ["dog", "albatross"]
Invokes the block with a Benchmark::Report object, which may be used to collect and report on the results of individual benchmark tests. Reserves label_width
leading spaces for labels on each line. Prints caption
at the top of the report, and uses format
to format each line. Returns an array of Benchmark::Tms
objects.
If the block returns an array of Benchmark::Tms
objects, these will be used to format additional lines of output. If labels
parameter are given, these are used to label these extra lines.
Note: Other methods provide a simpler interface to this one, and are suitable for nearly all benchmarking requirements. See the examples in Benchmark
, and the bm
and bmbm
methods.
Example:
require 'benchmark' include Benchmark # we need the CAPTION and FORMAT constants n = 5000000 Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| tf = x.report("for:") { for i in 1..n; a = "1"; end } tt = x.report("times:") { n.times do ; a = "1"; end } tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } [tf+tt+tu, (tf+tt+tu)/3] end
Generates:
user system total real for: 0.970000 0.000000 0.970000 ( 0.970493) times: 0.990000 0.000000 0.990000 ( 0.989542) upto: 0.970000 0.000000 0.970000 ( 0.972854) >total: 2.930000 0.000000 2.930000 ( 2.932889) >avg: 0.976667 0.000000 0.976667 ( 0.977630)
Invokes the block with a Benchmark::Report object, which may be used to collect and report on the results of individual benchmark tests. Reserves label_width
leading spaces for labels on each line. Prints caption
at the top of the report, and uses format
to format each line. Returns an array of Benchmark::Tms
objects.
If the block returns an array of Benchmark::Tms
objects, these will be used to format additional lines of output. If labels
parameter are given, these are used to label these extra lines.
Note: Other methods provide a simpler interface to this one, and are suitable for nearly all benchmarking requirements. See the examples in Benchmark
, and the bm
and bmbm
methods.
Example:
require 'benchmark' include Benchmark # we need the CAPTION and FORMAT constants n = 5000000 Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| tf = x.report("for:") { for i in 1..n; a = "1"; end } tt = x.report("times:") { n.times do ; a = "1"; end } tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } [tf+tt+tu, (tf+tt+tu)/3] end
Generates:
user system total real for: 0.970000 0.000000 0.970000 ( 0.970493) times: 0.990000 0.000000 0.990000 ( 0.989542) upto: 0.970000 0.000000 0.970000 ( 0.972854) >total: 2.930000 0.000000 2.930000 ( 2.932889) >avg: 0.976667 0.000000 0.976667 ( 0.977630)
Returns the currently set formatter. By default, it is set to DidYouMean::Formatter
.
Updates the primary formatter used to format the suggestions.