Returns a 2-element array containing the minimum-valued and maximum-valued elements from self
; does not modify self
.
With no block given, the minimum and maximum values are determined using method #<=>
:
[1, 0, 3, 2].minmax # => [0, 3]
With a block given, the block must return a numeric; the block is called self.size - 1
times to compare elements; returns the elements having the minimum and maximum values per the block:
['0', '', '000', '00'].minmax {|a, b| a.size <=> b.size } # => ["", "000"]
Related: see Methods for Fetching.
Returns a 2-element array containing the minimum and maximum value in self
, either according to comparison method #<=>
or a given block.
With no block given, returns the minimum and maximum values, using #<=>
for comparison:
(1..4).minmax # => [1, 4] (1...4).minmax # => [1, 3] ('a'..'d').minmax # => ["a", "d"] (-4..-1).minmax # => [-4, -1]
With a block given, the block must return an integer:
Negative if a
is smaller than b
.
Zero if a
and b
are equal.
Positive if a
is larger than b
.
The block is called self.size
times to compare elements; returns a 2-element Array
containing the minimum and maximum values from self
, per the block:
(1..4).minmax {|a, b| -(a <=> b) } # => [4, 1]
Returns [nil, nil]
if:
The begin value of the range is larger than the end value:
(4..1).minmax # => [nil, nil] (4..1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
The begin value of an exclusive range is equal to the end value:
(1...1).minmax # => [nil, nil] (1...1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
Raises an exception if self
is a beginless or an endless range.
Returns a 2-element array containing the minimum and maximum elements according to a given criterion. The ordering of equal elements is indeterminate and may be unstable.
With no argument and no block, returns the minimum and maximum elements, using the elements’ own method #<=>
for comparison:
(1..4).minmax # => [1, 4] (-4..-1).minmax # => [-4, -1] %w[d c b a].minmax # => ["a", "d"] {foo: 0, bar: 1, baz: 2}.minmax # => [[:bar, 1], [:foo, 0]] [].minmax # => [nil, nil]
With a block given, returns the minimum and maximum elements as determined by the block:
%w[xxx x xxxx xx].minmax {|a, b| a.size <=> b.size } # => ["x", "xxxx"] h = {foo: 0, bar: 1, baz: 2} h.minmax {|pair1, pair2| pair1[1] <=> pair2[1] } # => [[:foo, 0], [:baz, 2]] [].minmax {|a, b| a <=> b } # => [nil, nil]
Returns a 2-element array containing the elements for which the block returns minimum and maximum values:
(1..4).minmax_by {|element| -element } # => [4, 1] %w[a b c d].minmax_by {|element| -element.ord } # => ["d", "a"] {foo: 0, bar: 1, baz: 2}.minmax_by {|key, value| -value } # => [[:baz, 2], [:foo, 0]] [].minmax_by {|element| -element } # => [nil, nil]
Returns an Enumerator
if no block is given.
Raised when attempting to convert special float values (in particular Infinity
or NaN
) to numerical classes which don’t support them.
Float::INFINITY.to_r #=> FloatDomainError: Infinity
Objects of class Binding
encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self
, and possibly an iterator block that can be accessed in this context are all retained. Binding
objects can be created using Kernel#binding
, and are made available to the callback of Kernel#set_trace_func
and instances of TracePoint
.
These binding objects can be passed as the second argument of the Kernel#eval
method, establishing an environment for the evaluation.
class Demo def initialize(n) @secret = n end def get_binding binding end end k1 = Demo.new(99) b1 = k1.get_binding k2 = Demo.new(-3) b2 = k2.get_binding eval("@secret", b1) #=> 99 eval("@secret", b2) #=> -3 eval("@secret") #=> nil
Binding
objects have no class-specific methods.
In concurrent programming, a monitor is an object or module intended to be used safely by more than one thread. The defining characteristic of a monitor is that its methods are executed with mutual exclusion. That is, at each point in time, at most one thread may be executing any of its methods. This mutual exclusion greatly simplifies reasoning about the implementation of monitors compared to reasoning about parallel code that updates a data structure.
You can read more about the general principles on the Wikipedia page for Monitors.
require 'monitor.rb' buf = [] buf.extend(MonitorMixin) empty_cond = buf.new_cond # consumer Thread.start do loop do buf.synchronize do empty_cond.wait_while { buf.empty? } print buf.shift end end end # producer while line = ARGF.gets buf.synchronize do buf.push(line) empty_cond.signal end end
The consumer thread waits for the producer thread to push a line to buf while buf.empty?
. The producer thread (main thread) reads a line from ARGF
and pushes it into buf then calls empty_cond.signal
to notify the consumer thread of new data.
Class
include require 'monitor' class SynchronizedArray < Array include MonitorMixin def initialize(*args) super(*args) end alias :old_shift :shift alias :old_unshift :unshift def shift(n=1) self.synchronize do self.old_shift(n) end end def unshift(item) self.synchronize do self.old_unshift(item) end end # other methods ... end
SynchronizedArray
implements an Array
with synchronized access to items. This Class
is implemented as subclass of Array
which includes the MonitorMixin
module.
mkmf.rb is used by Ruby
C extensions to generate a Makefile which will correctly compile and link the C extension to Ruby
and a third-party library.
Raised when a gem dependencies file specifies a ruby version that does not match the current version.
Acts like a StringIO
with reduced API, but without having to require that class.
The original codebase emitted directly to $stderr, but now SyntaxError#detailed_message
needs a string output. To accomplish that we kept the original print infrastructure in place and added this class to accumulate the print output into a string.
This class is responsible for generating initial code blocks that will then later be expanded.
The biggest concern when guessing code blocks, is accidentally grabbing one that contains only an “end”. In this example:
def dog begonn # misspelled `begin` puts "bark" end end
The following lines would be matched (from bottom to top):
1) end 2) puts "bark" end 3) begonn puts "bark" end
At this point it has no where else to expand, and it will yield this inner code as a block
An Integer object represents an integer value.
You can create an Integer object explicitly with:
An integer literal.
You can convert certain objects to Integers with:
An attempt to add a singleton method to an instance of this class causes an exception to be raised.
First, what’s elsewhere. Class
Integer:
Inherits from class Numeric and class Object.
Includes module Comparable.
Here, class Integer provides methods for:
allbits?
: Returns whether all bits in self
are set.
anybits?
: Returns whether any bits in self
are set.
nobits?
: Returns whether no bits in self
are set.
<
: Returns whether self
is less than the given value.
<=
: Returns whether self
is less than or equal to the given value.
<=>
: Returns a number indicating whether self
is less than, equal to, or greater than the given value.
==
(aliased as ===
): Returns whether self
is equal to the given
value.
>
: Returns whether self
is greater than the given value.
>=
: Returns whether self
is greater than or equal to the given value.
::sqrt
: Returns the integer square root of the given value.
::try_convert
: Returns the given value converted to an Integer.
&
: Returns the bitwise AND of self
and the given value.
*
: Returns the product of self
and the given value.
**
: Returns the value of self
raised to the power of the given value.
+
: Returns the sum of self
and the given value.
-
: Returns the difference of self
and the given value.
/
: Returns the quotient of self
and the given value.
<<
: Returns the value of self
after a leftward bit-shift.
>>
: Returns the value of self
after a rightward bit-shift.
[]
: Returns a slice of bits from self
.
^
: Returns the bitwise EXCLUSIVE OR of self
and the given value.
|
: Returns the bitwise OR of self
and the given value.
ceil
: Returns the smallest number greater than or equal to self
.
chr
: Returns a 1-character string containing the character represented by the value of self
.
digits
: Returns an array of integers representing the base-radix digits of self
.
div
: Returns the integer result of dividing self
by the given value.
divmod
: Returns a 2-element array containing the quotient and remainder results of dividing self
by the given value.
fdiv
: Returns the Float
result of dividing self
by the given value.
floor
: Returns the greatest number smaller than or equal to self
.
pow
: Returns the modular exponentiation of self
.
pred
: Returns the integer predecessor of self
.
remainder
: Returns the remainder after dividing self
by the given value.
round
: Returns self
rounded to the nearest value with the given precision.
succ
(aliased as next
): Returns the integer successor of self
.
to_s
(aliased as inspect
): Returns a string containing the place-value representation of self
in the given radix.
truncate
: Returns self
truncated to the given precision.
A String
object has an arbitrary sequence of bytes, typically representing text or binary data. A String
object may be created using String::new
or as literals.
String
objects differ from Symbol
objects in that Symbol
objects are designed to be used as identifiers, instead of text or data.
You can create a String
object explicitly with:
A string literal.
A string literal.
You can convert certain objects to Strings with:
Some String
methods modify self
. Typically, a method whose name ends with !
modifies self
and returns self
; often, a similarly named method (without the !
) returns a new string.
In general, if both bang and non-bang versions of a method exist, the bang method mutates and the non-bang method does not. However, a method without a bang can also mutate, such as String#replace
.
These methods perform substitutions:
String#sub
: One substitution (or none); returns a new string.
String#sub!
: One substitution (or none); returns self
if any changes, nil
otherwise.
String#gsub
: Zero or more substitutions; returns a new string.
String#gsub!
: Zero or more substitutions; returns self
if any changes, nil
otherwise.
Each of these methods takes:
A first argument, pattern
(String
or Regexp
), that specifies the substring(s) to be replaced.
Either of the following:
The examples in this section mostly use the String#sub
and String#gsub
methods; the principles illustrated apply to all four substitution methods.
Argument pattern
Argument pattern
is commonly a regular expression:
s = 'hello' s.sub(/[aeiou]/, '*') # => "h*llo" s.gsub(/[aeiou]/, '*') # => "h*ll*" s.gsub(/[aeiou]/, '') # => "hll" s.sub(/ell/, 'al') # => "halo" s.gsub(/xyzzy/, '*') # => "hello" 'THX1138'.gsub(/\d+/, '00') # => "THX00"
When pattern
is a string, all its characters are treated as ordinary characters (not as Regexp
special characters):
'THX1138'.gsub('\d+', '00') # => "THX1138"
String
replacement
If replacement
is a string, that string determines the replacing string that is substituted for the matched text.
Each of the examples above uses a simple string as the replacing string.
String
replacement
may contain back-references to the pattern’s captures:
\n
(n is a non-negative integer) refers to $n
.
\k<name>
refers to the named capture name
.
See Regexp
for details.
Note that within the string replacement
, a character combination such as $&
is treated as ordinary text, not as a special match variable. However, you may refer to some special match variables using these combinations:
\&
and \0
correspond to $&
, which contains the complete matched text.
\'
corresponds to $'
, which contains the string after the match.
\`
corresponds to $`
, which contains the string before the match.
\+
corresponds to $+
, which contains the last capture group.
See Regexp
for details.
Note that \\
is interpreted as an escape, i.e., a single backslash.
Note also that a string literal consumes backslashes. See string literal for details about string literals.
A back-reference is typically preceded by an additional backslash. For example, if you want to write a back-reference \&
in replacement
with a double-quoted string literal, you need to write "..\\&.."
.
If you want to write a non-back-reference string \&
in replacement
, you need to first escape the backslash to prevent this method from interpreting it as a back-reference, and then you need to escape the backslashes again to prevent a string literal from consuming them: "..\\\\&.."
.
You may want to use the block form to avoid excessive backslashes.
Hash replacement
If the argument replacement
is a hash, and pattern
matches one of its keys, the replacing string is the value for that key:
h = {'foo' => 'bar', 'baz' => 'bat'} 'food'.sub('foo', h) # => "bard"
Note that a symbol key does not match:
h = {foo: 'bar', baz: 'bat'} 'food'.sub('foo', h) # => "d"
Block
In the block form, the current match string is passed to the block; the block’s return value becomes the replacing string:
s = '@' '1234'.gsub(/\d/) { |match| s.succ! } # => "ABCD"
Special match variables such as $1
, $2
, $`
, $&
, and $'
are set appropriately.
In the class String
, whitespace is defined as a contiguous sequence of characters consisting of any mixture of the following:
NL (null): "\x00"
, "\u0000"
.
HT (horizontal tab): "\x09"
, "\t"
.
LF (line feed): "\x0a"
, "\n"
.
VT (vertical tab): "\x0b"
, "\v"
.
FF (form feed): "\x0c"
, "\f"
.
CR (carriage return): "\x0d"
, "\r"
.
SP (space): "\x20"
, " "
.
Whitespace is relevant for the following methods:
String
Slices A slice of a string is a substring selected by certain criteria.
These instance methods utilize slicing:
String#[]
(aliased as String#slice
): Returns a slice copied from self
.
String#[]=
: Mutates self
with the slice replaced.
String#slice!
: Mutates self
with the slice removed and returns the removed slice.
Each of the above methods takes arguments that determine the slice to be copied or replaced.
The arguments have several forms. For a string string
, the forms are:
string[index]
string[start, length]
string[range]
string[regexp, capture = 0]
string[substring]
string[index]
When a non-negative integer argument index
is given, the slice is the 1-character substring found in self
at character offset index
:
'bar'[0] # => "b" 'bar'[2] # => "r" 'bar'[20] # => nil 'тест'[2] # => "с" 'こんにちは'[4] # => "は"
When a negative integer index
is given, the slice begins at the offset given by counting backward from the end of self
:
'bar'[-3] # => "b" 'bar'[-1] # => "r" 'bar'[-20] # => nil
string[start, length]
When non-negative integer arguments start
and length
are given, the slice begins at character offset start
, if it exists, and continues for length
characters, if available:
'foo'[0, 2] # => "fo" 'тест'[1, 2] # => "ес" 'こんにちは'[2, 2] # => "にち" # Zero length. 'foo'[2, 0] # => "" # Length not entirely available. 'foo'[1, 200] # => "oo" # Start out of range. 'foo'[4, 2] # => nil
Special case: if start
equals the length of self
, the slice is a new empty string:
'foo'[3, 2] # => "" 'foo'[3, 200] # => ""
When a negative start
and non-negative length
are given, the slice begins by counting backward from the end of self
, and continues for length
characters, if available:
'foo'[-2, 2] # => "oo" 'foo'[-2, 200] # => "oo" # Start out of range. 'foo'[-4, 2] # => nil
When a negative length
is given, there is no slice:
'foo'[1, -1] # => nil 'foo'[-2, -1] # => nil
string[range]
When a Range
argument range
is given, it creates a substring of string
using the indices in range
. The slice is then determined as above:
'foo'[0..1] # => "fo" 'foo'[0, 2] # => "fo" 'foo'[2...2] # => "" 'foo'[2, 0] # => "" 'foo'[1..200] # => "oo" 'foo'[1, 200] # => "oo" 'foo'[4..5] # => nil 'foo'[4, 2] # => nil 'foo'[-4..-3] # => nil 'foo'[-4, 2] # => nil 'foo'[3..4] # => "" 'foo'[3, 2] # => "" 'foo'[-2..-1] # => "oo" 'foo'[-2, 2] # => "oo" 'foo'[-2..197] # => "oo" 'foo'[-2, 200] # => "oo"
string[regexp, capture = 0]
When the Regexp
argument regexp
is given, and the capture
argument is 0
, the slice is the first matching substring found in self
:
'foo'[/o/] # => "o" 'foo'[/x/] # => nil s = 'hello there' s[/[aeiou](.)\1/] # => "ell" s[/[aeiou](.)\1/, 0] # => "ell"
If the argument capture
is provided and not 0
, it should be either a capture group index (integer) or a capture group name (String
or Symbol
); the slice is the specified capture (see Groups at Regexp
and Captures):
s = 'hello there' s[/[aeiou](.)\1/, 1] # => "l" s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "non_vowel"] # => "l" s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, :vowel] # => "e"
If an invalid capture group index is given, there is no slice. If an invalid capture group name is given, IndexError
is raised.
string[substring]
When the single String
argument substring
is given, it returns the substring from self
if found, otherwise nil
:
'foo'['oo'] # => "oo" 'foo'['xx'] # => nil
First, what’s elsewhere. Class
String
:
Inherits from the Object class.
Includes the Comparable module.
Here, class String
provides methods that are useful for:
String
::new
: Returns a new string.
::try_convert
: Returns a new string created from a given object.
String
+@
: Returns a string that is not frozen: self
if not frozen; self.dup
otherwise.
-@
(aliased as dedup
): Returns a string that is frozen: self
if already frozen; self.freeze
otherwise.
freeze
: Freezes self
if not already frozen; returns self
.
Counts
length
(aliased as size
): Returns the count of characters (not bytes).
empty?
: Returns true
if self.length
is zero; false
otherwise.
bytesize
: Returns the count of bytes.
count
: Returns the count of substrings matching given strings.
Substrings
=~
: Returns the index of the first substring that matches a given Regexp
or other object; returns nil
if no match is found.
index
: Returns the index of the first occurrence of a given substring; returns nil
if none found.
rindex
: Returns the index of the last occurrence of a given substring; returns nil
if none found.
include?
: Returns true
if the string contains a given substring; false
otherwise.
match
: Returns a MatchData
object if the string matches a given Regexp
; nil
otherwise.
match?
: Returns true
if the string matches a given Regexp
; false
otherwise.
start_with?
: Returns true
if the string begins with any of the given substrings.
end_with?
: Returns true
if the string ends with any of the given substrings.
Encodings
encoding
: Returns the Encoding
object that represents the encoding of the string.
unicode_normalized?
: Returns true
if the string is in Unicode normalized form; false
otherwise.
valid_encoding?
: Returns true
if the string contains only characters that are valid for its encoding.
ascii_only?
: Returns true
if the string has only ASCII characters; false
otherwise.
Other
sum
: Returns a basic checksum for the string: the sum of each byte.
hash
: Returns the integer hash code.
==
(aliased as ===
): Returns true
if a given other string has the same content as self
.
eql?
: Returns true
if the content is the same as the given other string.
<=>
: Returns -1, 0, or 1 as a given other string is smaller than, equal to, or larger than self
.
casecmp
: Ignoring case, returns -1, 0, or 1 as a given other string is smaller than, equal to, or larger than self
.
casecmp?
: Returns true
if the string is equal to a given string after Unicode case folding; false
otherwise.
String
Each of these methods modifies self
.
Insertion
insert
: Returns self
with a given string inserted at a specified offset.
<<
: Returns self
concatenated with a given string or integer.
append_as_bytes
: Returns self
concatenated with strings without performing any encoding validation or conversion.
Substitution
sub!
: Replaces the first substring that matches a given pattern with a given replacement string; returns self
if any changes, nil
otherwise.
gsub!
: Replaces each substring that matches a given pattern with a given replacement string; returns self
if any changes, nil
otherwise.
succ!
(aliased as next!
): Returns self
modified to become its own successor.
initialize_copy
(aliased as replace
): Returns self
with its entire content replaced by a given string.
reverse!
: Returns self
with its characters in reverse order.
setbyte
: Sets the byte at a given integer offset to a given value; returns the argument.
tr!
: Replaces specified characters in self
with specified replacement characters; returns self
if any changes, nil
otherwise.
tr_s!
: Replaces specified characters in self
with specified replacement characters, removing duplicates from the substrings that were modified; returns self
if any changes, nil
otherwise.
Casing
capitalize!
: Upcases the initial character and downcases all others; returns self
if any changes, nil
otherwise.
downcase!
: Downcases all characters; returns self
if any changes, nil
otherwise.
upcase!
: Upcases all characters; returns self
if any changes, nil
otherwise.
swapcase!
: Upcases each downcase character and downcases each upcase character; returns self
if any changes, nil
otherwise.
Encoding
encode!
: Returns self
with all characters transcoded from one encoding to another.
unicode_normalize!
: Unicode-normalizes self
; returns self
.
scrub!
: Replaces each invalid byte with a given character; returns self
.
force_encoding
: Changes the encoding to a given encoding; returns self
.
Deletion
clear
: Removes all content, so that self
is empty; returns self
.
slice!
, []=
: Removes a substring determined by a given index, start/length, range, regexp, or substring.
squeeze!
: Removes contiguous duplicate characters; returns self
.
delete!
: Removes characters as determined by the intersection of substring arguments.
lstrip!
: Removes leading whitespace; returns self
if any changes, nil
otherwise.
rstrip!
: Removes trailing whitespace; returns self
if any changes, nil
otherwise.
strip!
: Removes leading and trailing whitespace; returns self
if any changes, nil
otherwise.
chomp!
: Removes the trailing record separator, if found; returns self
if any changes, nil
otherwise.
chop!
: Removes trailing newline characters if found; otherwise removes the last character; returns self
if any changes, nil
otherwise.
String
Each of these methods returns a new String
based on self
, often just a modified copy of self
.
Extension
*
: Returns the concatenation of multiple copies of self
.
+
: Returns the concatenation of self
and a given other string.
center
: Returns a copy of self
centered between pad substrings.
concat
: Returns the concatenation of self
with given other strings.
prepend
: Returns the concatenation of a given other string with self
.
ljust
: Returns a copy of self
of a given length, right-padded with a given other string.
rjust
: Returns a copy of self
of a given length, left-padded with a given other string.
Encoding
b
: Returns a copy of self
with ASCII-8BIT encoding.
scrub
: Returns a copy of self
with each invalid byte replaced with a given character.
unicode_normalize
: Returns a copy of self
with each character Unicode-normalized.
encode
: Returns a copy of self
with all characters transcoded from one encoding to another.
Substitution
dump
: Returns a copy of self
with all non-printing characters replaced by xHH notation and all special characters escaped.
undump
: Returns a copy of self
with all \xNN
notations replaced by \uNNNN
notations and all escaped characters unescaped.
sub
: Returns a copy of self
with the first substring matching a given pattern replaced with a given replacement string.
gsub
: Returns a copy of self
with each substring that matches a given pattern replaced with a given replacement string.
succ
(aliased as next
): Returns the string that is the successor to self
.
reverse
: Returns a copy of self
with its characters in reverse order.
tr
: Returns a copy of self
with specified characters replaced with specified replacement characters.
tr_s
: Returns a copy of self
with specified characters replaced with specified replacement characters, removing duplicates from the substrings that were modified.
%
: Returns the string resulting from formatting a given object into self
.
Casing
capitalize
: Returns a copy of self
with the first character upcased and all other characters downcased.
downcase
: Returns a copy of self
with all characters downcased.
upcase
: Returns a copy of self
with all characters upcased.
swapcase
: Returns a copy of self
with all upcase characters downcased and all downcase characters upcased.
Deletion
delete
: Returns a copy of self
with characters removed.
delete_prefix
: Returns a copy of self
with a given prefix removed.
delete_suffix
: Returns a copy of self
with a given suffix removed.
lstrip
: Returns a copy of self
with leading whitespace removed.
rstrip
: Returns a copy of self
with trailing whitespace removed.
strip
: Returns a copy of self
with leading and trailing whitespace removed.
chomp
: Returns a copy of self
with a trailing record separator removed, if found.
chop
: Returns a copy of self
with trailing newline characters or the last character removed.
squeeze
: Returns a copy of self
with contiguous duplicate characters removed.
[]
(aliased as slice
): Returns a substring determined by a given index, start/length, range, regexp, or string.
byteslice
: Returns a substring determined by a given index, start/length, or range.
chr
: Returns the first character.
Duplication
to_s
(aliased as to_str
): If self
is a subclass of String
, returns self
copied into a String
; otherwise, returns self
.
String
Each of these methods converts the contents of self
to a non-String
.
Characters, Bytes, and Clusters
bytes
: Returns an array of the bytes in self
.
chars
: Returns an array of the characters in self
.
codepoints
: Returns an array of the integer ordinals in self
.
getbyte
: Returns the integer byte at the given index in self
.
grapheme_clusters
: Returns an array of the grapheme clusters in self
.
Splitting
lines
: Returns an array of the lines in self
, as determined by a given record separator.
partition
: Returns a 3-element array determined by the first substring that matches a given substring or regexp.
rpartition
: Returns a 3-element array determined by the last substring that matches a given substring or regexp.
split
: Returns an array of substrings determined by a given delimiter – regexp or string – or, if a block is given, passes those substrings to the block.
Matching
scan
: Returns an array of substrings matching a given regexp or string, or, if a block is given, passes each matching substring to the block.
unpack
: Returns an array of substrings extracted from self
according to a given format.
unpack1
: Returns the first substring extracted from self
according to a given format.
Numerics
hex
: Returns the integer value of the leading characters, interpreted as hexadecimal digits.
oct
: Returns the integer value of the leading characters, interpreted as octal digits.
ord
: Returns the integer ordinal of the first character in self
.
to_i
: Returns the integer value of leading characters, interpreted as an integer.
to_f
: Returns the floating-point value of leading characters, interpreted as a floating-point number.
Strings and Symbols
inspect
: Returns a copy of self
, enclosed in double quotes, with special characters escaped.
intern
(aliased as to_sym
): Returns the symbol corresponding to self
.
each_byte
: Calls the given block with each successive byte in self
.
each_char
: Calls the given block with each successive character in self
.
each_codepoint
: Calls the given block with each successive integer codepoint in self
.
each_grapheme_cluster
: Calls the given block with each successive grapheme cluster in self
.
each_line
: Calls the given block with each successive line in self
, as determined by a given record separator.
upto
: Calls the given block with each string value returned by successive calls to succ
.
Continuation
objects are generated by Kernel#callcc
, after having +require+d continuation. They hold a return address and execution context, allowing a nonlocal return to the end of the callcc
block from anywhere within a program. Continuations are somewhat analogous to a structured version of C’s setjmp/longjmp
(although they contain more state, so you might consider them closer to threads).
For instance:
require "continuation" arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ] callcc{|cc| $cc = cc} puts(message = arr.shift) $cc.call unless message =~ /Max/
produces:
Freddie Herbie Ron Max
Also you can call callcc in other methods:
require "continuation" def g arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ] cc = callcc { |cc| cc } puts arr.shift return cc, arr.size end def f c, size = g c.call(c) if size > 1 end f
This (somewhat contrived) example allows the inner loop to abandon processing early:
require "continuation" callcc {|cont| for i in 0..4 print "#{i}: " for j in i*5...(i+1)*5 cont.call() if j == 17 printf "%3d", j end end } puts
produces:
0: 0 1 2 3 4 1: 5 6 7 8 9 2: 10 11 12 13 14 3: 15 16
An Encoding instance represents a character encoding usable in Ruby
. It is defined as a constant under the Encoding namespace. It has a name and, optionally, aliases:
Encoding::US_ASCII.name # => "US-ASCII" Encoding::US_ASCII.names # => ["US-ASCII", "ASCII", "ANSI_X3.4-1968", "646"]
A Ruby
method that accepts an encoding as an argument will accept:
An Encoding object.
The name of an encoding.
An alias for an encoding name.
These are equivalent:
'foo'.encode(Encoding::US_ASCII) # Encoding object. 'foo'.encode('US-ASCII') # Encoding name. 'foo'.encode('ASCII') # Encoding alias.
For a full discussion of encodings and their uses, see the Encodings document.
Encoding::ASCII_8BIT is a special-purpose encoding that is usually used for a string of bytes, not a string of characters. But as the name indicates, its characters in the ASCII range are considered as ASCII characters. This is useful when you use other ASCII-compatible encodings.
Raised when the interrupt signal is received, typically because the user has pressed Control-C (on most posix platforms). As such, it is a subclass of SignalException
.
begin puts "Press ctrl-C when you get bored" loop {} rescue Interrupt => e puts "Note: You will typically use Signal.trap instead." end
produces:
Press ctrl-C when you get bored
then waits until it is interrupted with Control-C and then prints:
Note: You will typically use Signal.trap instead.
Raised when the given index is invalid.
a = [:foo, :bar] a.fetch(0) #=> :foo a[4] #=> nil a.fetch(4) #=> IndexError: index 4 outside of array bounds: -2...2
Raised when encountering Ruby
code with an invalid syntax.
eval("1+1=2")
raises the exception:
SyntaxError: (eval):1: syntax error, unexpected '=', expecting $end
EncodingError
is the base class for encoding errors.
The Addrinfo
class maps struct addrinfo
to ruby. This structure identifies an Internet host and a service.