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:
Method String
.
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 there exist both bang and non-bang version of method, the bang! mutates and the non-bang! 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
.
String#gsub
: Zero or more substitutions; returns a new string.
String#gsub!
: Zero or more substitutions; returns self
.
Each of these methods takes:
A first argument, pattern
(string or regexp), that specifies the substring(s) to be replaced.
Either of these:
A second argument, replacement
(string or hash), that determines the replacing string.
A block that will determine the replacing string.
The examples in this section mostly use methods String#sub
and String#gsub
; 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 will determine the replacing string that is to be 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 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, and 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 string after match.
\`
corresponds to $`
, which contains string before match.
\+
corresponds to $+
, which contains 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 first to 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 a lot of backslashes.
Hash replacement
If 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 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 these methods:
A slice of a string is a substring that is selected by certain criteria.
These instance methods make use of slicing:
String#[]
(also aliased as String#slice
) returns a slice copied from self
.
String#[]=
returns a copy of self
with a slice replaced.
String#slice!
returns self
with a slice removed.
Each of the above methods takes arguments that determine the slice to be copied or replaced.
The arguments have several forms. For string string
, the forms are:
string[index]
.
string[start, length]
.
string[range]
.
string[regexp, capture = 0]
.
string[substring]
.
string[index]
When 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 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
is equal to the length of self
, the slice is a new empty string:
'foo'[3, 2] # => "" 'foo'[3, 200] # => ""
When negative start
and non-negative length
are given, the slice beginning is determined by counting backward from the end of self
, and the slice continues for length
characters, if available:
'foo'[-2, 2] # => "oo" 'foo'[-2, 200] # => "oo" # Start out of range. 'foo'[-4, 2] # => nil
When negative length
is given, there is no slice:
'foo'[1, -1] # => nil 'foo'[-2, -1] # => nil
string[range]
When Range
argument range
is given, 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 argument capture
is given and not 0
, it should be either an capture group index (integer) or a capture group name (string or symbol); the slice is the specified capture (see Groups and Captures at Regexp
):
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, returns the substring from self
if found, otherwise nil
:
'foo'['oo'] # => "oo" 'foo'['xx'] # => nil
First, what’s elsewhere. Class String:
Inherits from class Object.
Includes module Comparable.
Here, class String provides methods that are useful for:
::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.
-@
: Returns a string that is frozen: self
, if already frozen; self.freeze
otherwise.
freeze
: Freezes self
, if not already frozen; returns self
.
Counts
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.
==
, ===
: 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.
Each of these methods modifies self
.
Insertion
insert
: Returns self
with a given string inserted at a given offset.
<<
: Returns self
concatenated with a given string or integer.
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!
, next!
: Returns self
modified to become its own successor.
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 given encoding into 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 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.
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 substring.
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 given encoding into 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
notation replace by \uNNNN
notation 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
, 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.
[]
, slice
: Returns a substring determined by a given index, start/length, or range, or string.
byteslice
: Returns a substring determined by a given index, start/length, or range.
chr
: Returns the first character.
Duplication
to_s
, $to_str: If self
is a subclass of String, returns self
copied into a String; otherwise, returns self
.
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 an integer byte as determined by a given index.
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 given, passes those substrings to the block.
Matching
scan
: Returns an array of substrings matching a given regexp or string, or, if a block 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 copy of self
, enclosed in double-quotes, with special characters escaped.
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
.
Returns the substring of self
specified by the arguments. See examples at String Slices.
Returns a new array populated with the given objects.
Array.[]( 1, 'a', /^A/) # => [1, "a", /^A/] Array[ 1, 'a', /^A/ ] # => [1, "a", /^A/] [ 1, 'a', /^A/ ] # => [1, "a", /^A/]
Returns elements from self
; does not modify self
.
When a single Integer
argument index
is given, returns the element at offset index
:
a = [:foo, 'bar', 2] a[0] # => :foo a[2] # => 2 a # => [:foo, "bar", 2]
If index
is negative, counts relative to the end of self
:
a = [:foo, 'bar', 2] a[-1] # => 2 a[-2] # => "bar"
If index
is out of range, returns nil
.
When two Integer
arguments start
and length
are given, returns a new Array of size length
containing successive elements beginning at offset start
:
a = [:foo, 'bar', 2] a[0, 2] # => [:foo, "bar"] a[1, 2] # => ["bar", 2]
If start + length
is greater than self.length
, returns all elements from offset start
to the end:
a = [:foo, 'bar', 2] a[0, 4] # => [:foo, "bar", 2] a[1, 3] # => ["bar", 2] a[2, 2] # => [2]
If start == self.size
and length >= 0
, returns a new empty Array.
If length
is negative, returns nil
.
When a single Range
argument range
is given, treats range.min
as start
above and range.size
as length
above:
a = [:foo, 'bar', 2] a[0..1] # => [:foo, "bar"] a[1..2] # => ["bar", 2]
Special case: If range.start == a.size
, returns a new empty Array.
If range.end
is negative, calculates the end index from the end:
a = [:foo, 'bar', 2] a[0..-1] # => [:foo, "bar", 2] a[0..-2] # => [:foo, "bar"] a[0..-3] # => [:foo]
If range.start
is negative, calculates the start index from the end:
a = [:foo, 'bar', 2] a[-1..2] # => [2] a[-2..2] # => ["bar", 2] a[-3..2] # => [:foo, "bar", 2]
If range.start
is larger than the array size, returns nil
.
a = [:foo, 'bar', 2] a[4..1] # => nil a[4..0] # => nil a[4..-1] # => nil
When a single Enumerator::ArithmeticSequence
argument aseq
is given, returns an Array of elements corresponding to the indexes produced by the sequence.
a = ['--', 'data1', '--', 'data2', '--', 'data3'] a[(1..).step(2)] # => ["data1", "data2", "data3"]
Unlike slicing with range, if the start or the end of the arithmetic sequence is larger than array size, throws RangeError
.
a = ['--', 'data1', '--', 'data2', '--', 'data3'] a[(1..11).step(2)] # RangeError (((1..11).step(2)) out of range) a[(7..).step(2)] # RangeError (((7..).step(2)) out of range)
If given a single argument, and its type is not one of the listed, tries to convert it to Integer
, and raises if it is impossible:
a = [:foo, 'bar', 2] # Raises TypeError (no implicit conversion of Symbol into Integer): a[:foo]
Returns a slice of bits from self
.
With argument offset
, returns the bit at the given offset, where offset 0 refers to the least significant bit:
n = 0b10 # => 2 n[0] # => 0 n[1] # => 1 n[2] # => 0 n[3] # => 0
In principle, n[i]
is equivalent to (n >> i) & 1
. Thus, negative index always returns zero:
255[-1] # => 0
With arguments offset
and size
, returns size
bits from self
, beginning at offset
and including bits of greater significance:
n = 0b111000 # => 56 "%010b" % n[0, 10] # => "0000111000" "%010b" % n[4, 10] # => "0000000011"
With argument range
, returns range.size
bits from self
, beginning at range.begin
and including bits of greater significance:
n = 0b111000 # => 56 "%010b" % n[0..9] # => "0000111000" "%010b" % n[4..9] # => "0000000011"
Raises an exception if the slice cannot be constructed.
Returns the value of the fiber storage variable identified by key
.
The key
must be a symbol, and the value is set by Fiber#[]= or Fiber#store.
See also Fiber::[]=
.
Invokes the continuation. The program continues from the end of the callcc
block. If no arguments are given, the original callcc
returns nil
. If one argument is given, callcc
returns it. Otherwise, an array containing args is returned.
callcc {|cont| cont.call } #=> nil callcc {|cont| cont.call 1 } #=> 1 callcc {|cont| cont.call 1, 2, 3 } #=> [1, 2, 3]
Calls Dir.glob
with argument patterns
and the values of keyword arguments base
and sort
; returns the array of selected entry names.
Returns the value of an attribute, or nil
if there is no such attribute.
require "ostruct" person = OpenStruct.new("name" => "John Smith", "age" => 70) person[:age] # => 70, same as person.age
Creates a new set containing the given objects.
Set[1, 2] # => #<Set: {1, 2}> Set[1, 2, 1] # => #<Set: {1, 2}> Set[1, 'c', :s] # => #<Set: {1, "c", :s}>
Returns a value from self
.
With symbol or string argument name
given, returns the value for the named member:
Customer = Struct.new(:name, :address, :zip) joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345) joe[:zip] # => 12345
Raises NameError
if name
is not the name of a member.
With integer argument n
given, returns self.values[n]
if n
is in range; see Array Indexes at Array
:
joe[2] # => 12345 joe[-2] # => "123 Maple, Anytown NC"
Raises IndexError
if n
is out of range.
Returns the n-th subgroup in the most recent match.
s = StringScanner.new("Fri Dec 12 1975 14:39") s.scan(/(\w+) (\w+) (\d+) /) # -> "Fri Dec 12 " s[0] # -> "Fri Dec 12 " s[1] # -> "Fri" s[2] # -> "Dec" s[3] # -> "12" s.post_match # -> "1975 14:39" s.pre_match # -> "" s.reset s.scan(/(?<wday>\w+) (?<month>\w+) (?<day>\d+) /) # -> "Fri Dec 12 " s[0] # -> "Fri Dec 12 " s[1] # -> "Fri" s[2] # -> "Dec" s[3] # -> "12" s[:wday] # -> "Fri" s[:month] # -> "Dec" s[:day] # -> "12" s.post_match # -> "1975 14:39" s.pre_match # -> ""
Returns the value of Collection specified by a1, a2,.…
dict = WIN32OLE.new('Scripting.Dictionary') dict.add('ruby', 'Ruby') puts dict['ruby'] # => 'Ruby' (same as `puts dict.item('ruby')')
Remark: You can not use this method to get the property.
excel = WIN32OLE.new('Excel.Application') # puts excel['Visible'] This is error !!! puts excel.Visible # You should to use this style to get the property.
Returns a new Hash object populated with the given objects, if any. See Hash::new
.
With no argument, returns a new empty Hash.
When the single given argument is a Hash, returns a new Hash populated with the entries from the given Hash, excluding the default value or proc.
h = {foo: 0, bar: 1, baz: 2} Hash[h] # => {:foo=>0, :bar=>1, :baz=>2}
When the single given argument is an Array
of 2-element Arrays, returns a new Hash object wherein each 2-element array forms a key-value entry:
Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {:foo=>0, :bar=>1}
When the argument count is an even number; returns a new Hash object wherein each successive pair of arguments has become a key-value entry:
Hash[:foo, 0, :bar, 1] # => {:foo=>0, :bar=>1}
Raises an exception if the argument list does not conform to any of the above.
Returns the value associated with the given key
, if found:
h = {foo: 0, bar: 1, baz: 2} h[:foo] # => 0
If key
is not found, returns a default value (see Default Values):
h = {foo: 0, bar: 1, baz: 2} h[:nosuch] # => nil
Returns the value for the environment variable name
if it exists:
ENV['foo'] = '0' ENV['foo'] # => "0"
Returns nil
if the named variable does not exist.
Raises an exception if name
is invalid. See Invalid Names and Values.
When arguments index
, +start and length
, or range
are given, returns match and captures in the style of Array#[]
:
m = /(.)(.)(\d+)(\d)/.match("THX1138.") # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8"> m[0] # => "HX1138" m[1, 2] # => ["H", "X"] m[1..3] # => ["H", "X", "113"] m[-3, 2] # => ["X", "113"]
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['foo'] # => "h" m[:bar] # => "ge"
If multiple captures have the same name, returns the last matched substring.
m = /(?<foo>.)(?<foo>.+)/.match("hoge") # => #<MatchData "hoge" foo:"h" foo:"oge"> m[:foo] #=> "oge" m = /\W(?<foo>.+)|\w(?<foo>.+)|(?<foo>.+)/.match("hoge") #<MatchData "hoge" foo:nil foo:"oge" foo:nil> m[:foo] #=> "oge"
Returns the value for the given key
if the key exists. nil
otherwise; if not nil
, the returned value is an object or a hierarchy of objects:
example_store do |store| store.transaction do store[:foo] # => 0 store[:nope] # => nil end end
Returns nil
if there is no such key.
See also Hierarchical Values.
Raises an exception if called outside a transaction block.
Invokes the block, setting the block’s parameters to the values in params using something close to method calling semantics. Returns the value of the last expression evaluated in the block.
a_proc = Proc.new {|scalar, *values| values.map {|value| value*scalar } } a_proc.call(9, 1, 2, 3) #=> [9, 18, 27] a_proc[9, 1, 2, 3] #=> [9, 18, 27] a_proc.(9, 1, 2, 3) #=> [9, 18, 27] a_proc.yield(9, 1, 2, 3) #=> [9, 18, 27]
Note that prc.()
invokes prc.call()
with the parameters given. It’s syntactic sugar to hide “call”.
For procs created using lambda
or ->()
an error is generated if the wrong number of parameters are passed to the proc. For procs created using Proc.new
or Kernel.proc
, extra parameters are silently discarded and missing parameters are set to nil
.
a_proc = proc {|a,b| [a,b] } a_proc.call(1) #=> [1, nil] a_proc = lambda {|a,b| [a,b] } a_proc.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
See also Proc#lambda?
.
Invokes the meth with the specified arguments, returning the method’s return value.
m = 12.method("+") m.call(3) #=> 15 m.call(20) #=> 32
get a value from ractor-local storage
Attribute Reference—Returns the value of a fiber-local variable (current thread’s root fiber if not explicitly inside a Fiber
), using either a symbol or a string name. If the specified variable does not exist, returns nil
.
[ Thread.new { Thread.current["name"] = "A" }, Thread.new { Thread.current[:name] = "B" }, Thread.new { Thread.current["name"] = "C" } ].each do |th| th.join puts "#{th.inspect}: #{th[:name]}" end
This will produce:
#<Thread:0x00000002a54220 dead>: A #<Thread:0x00000002a541a8 dead>: B #<Thread:0x00000002a54130 dead>: C
Thread#[]
and Thread#[]=
are not thread-local but fiber-local. This confusion did not exist in Ruby 1.8 because fibers are only available since Ruby 1.9. Ruby 1.9 chooses that the methods behaves fiber-local to save following idiom for dynamic scope.
def meth(newvalue) begin oldvalue = Thread.current[:name] Thread.current[:name] = newvalue yield ensure Thread.current[:name] = oldvalue end end
The idiom may not work as dynamic scope if the methods are thread-local and a given block switches fiber.
f = Fiber.new { meth(1) { Fiber.yield } } meth(2) { f.resume } f.resume p Thread.current[:name] #=> nil if fiber-local #=> 2 if thread-local (The value 2 is leaked to outside of meth method.)
For thread-local variables, please see thread_variable_get
and thread_variable_set
.