Installs a gem along with all its dependencies from local and remote gems.
Raised when there are conflicting gem specs loaded
Raised when removing a gem with the uninstall command fails
Potentially raised when a specification is validated.
The installer installs the files contained in the .gem into the Gem.home.
Gem::Installer
does the work of putting files in all the right places on the filesystem including unpacking the gem into its gem dir, installing the gemspec in the specifications dir, storing the cached gem in the cache dir, and installing either wrappers or symlinks for executables.
The installer invokes pre and post install hooks. Hooks can be added either through a rubygems_plugin.rb file in an installed gem or via a rubygems/defaults/#{RUBY_ENGINE}.rb or rubygems/defaults/operating_system.rb file. See Gem.pre_install
and Gem.post_install
for details.
Gem::StubSpecification
reads the stub: line from the gemspec. This prevents us having to eval the entire gemspec in order to find out certain information.
An Uninstaller
.
The uninstaller fires pre and post uninstall hooks. Hooks can be added either through a rubygems_plugin.rb file in an installed gem or via a rubygems/defaults/#{RUBY_ENGINE}.rb or rubygems/defaults/operating_system.rb file. See Gem.pre_uninstall
and Gem.post_uninstall
for details.
Not a URI
component.
This module provides instance methods for a digest implementation object to calculate message digest values.
This module contains configuration information about the SSL
extension, for example if socket support is enabled, or the host name TLS extension is enabled. Constants in this module will always be defined, but contain true
or false
values depending on the configuration of your OpenSSL
installation.
Mixin module that provides the following:
Access to the CGI
environment variables as methods. See documentation to the CGI
class for a list of these variables. The methods are exposed by removing the leading HTTP_
(if it exists) and downcasing the name. For example, auth_type
will return the environment variable AUTH_TYPE
, and accept
will return the value for HTTP_ACCEPT
.
Access to cookies, including the cookies attribute.
Access to parameters, including the params attribute, and overloading []
to perform parameter value lookup by key.
The initialize_query
method, for initializing the above mechanisms, handling multipart forms, and allowing the class to be used in “offline” mode.
Mixin module providing HTML generation methods.
For example,
cgi.a("http://www.example.com") { "Example" } # => "<A HREF=\"http://www.example.com\">Example</A>"
Modules Html3, Html4, etc., contain more basic HTML-generation methods (#title
, #h1
, etc.).
See class CGI
for a detailed example.
Net::HTTP
exception class. You cannot use Net::HTTPExceptions
directly; instead, you must use its subclasses.
Keyword completion module. This allows partial arguments to be specified and resolved against a list of acceptable values.
A complex number can be represented as a paired real number with imaginary unit; a+bi. Where a is real part, b is imaginary part and i is imaginary unit. Real a equals complex a+0i mathematically.
You can create a Complex object explicitly with:
You can convert certain objects to Complex objects with:
Method Complex.
Complex
object can be created as literal, and also by using Kernel#Complex
, Complex::rect
, Complex::polar
or to_c
method.
2+1i #=> (2+1i) Complex(1) #=> (1+0i) Complex(2, 3) #=> (2+3i) Complex.polar(2, 3) #=> (-1.9799849932008908+0.2822400161197344i) 3.to_c #=> (3+0i)
You can also create complex object from floating-point numbers or strings.
Complex(0.3) #=> (0.3+0i) Complex('0.3-0.5i') #=> (0.3-0.5i) Complex('2/3+3/4i') #=> ((2/3)+(3/4)*i) Complex('1@2') #=> (-0.4161468365471424+0.9092974268256817i) 0.3.to_c #=> (0.3+0i) '0.3-0.5i'.to_c #=> (0.3-0.5i) '2/3+3/4i'.to_c #=> ((2/3)+(3/4)*i) '1@2'.to_c #=> (-0.4161468365471424+0.9092974268256817i)
A complex object is either an exact or an inexact number.
Complex(1, 1) / 2 #=> ((1/2)+(1/2)*i) Complex(1, 1) / 2.0 #=> (0.5+0.5i)
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:
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.rdoc 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.rdoc for details.
Note that \\
is interpreted as an escape, i.e., a single backslash.
Note also that a string literal consumes backslashes. See String Literals 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.
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
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.
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
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.
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
.
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 whitespace 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.
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 whitespace or the last character removed.
squeeze
Returns a copy of self
with contiguous duplicate characters removed.
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.
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::ISO_8859_1.name #=> "ISO-8859-1" Encoding::ISO_8859_1.names #=> ["ISO-8859-1", "ISO8859-1"]
Ruby methods dealing with encodings return or accept Encoding
instances as arguments (when a method accepts an Encoding
instance as an argument, it can be passed an Encoding
name or alias instead).
"some string".encoding #=> #<Encoding:UTF-8> string = "some string".encode(Encoding::ISO_8859_1) #=> "some string" string.encoding #=> #<Encoding:ISO-8859-1> "some string".encode "ISO-8859-1" #=> "some string"
Encoding::ASCII_8BIT is a special encoding that is usually used for a byte string, not a character string. But as the name insists, its characters in the range of ASCII are considered as ASCII characters. This is useful when you use ASCII-8BIT characters with other ASCII compatible characters.
The associated Encoding
of a String
can be changed in two different ways.
First, it is possible to set the Encoding
of a string to a new Encoding
without changing the internal byte representation of the string, with String#force_encoding
. This is how you can tell Ruby the correct encoding of a string.
string #=> "R\xC3\xA9sum\xC3\xA9" string.encoding #=> #<Encoding:ISO-8859-1> string.force_encoding(Encoding::UTF_8) #=> "R\u00E9sum\u00E9"
Second, it is possible to transcode a string, i.e. translate its internal byte representation to another encoding. Its associated encoding is also set to the other encoding. See String#encode
for the various forms of transcoding, and the Encoding::Converter
class for additional control over the transcoding process.
string #=> "R\u00E9sum\u00E9" string.encoding #=> #<Encoding:UTF-8> string = string.encode!(Encoding::ISO_8859_1) #=> "R\xE9sum\xE9" string.encoding #=> #<Encoding::ISO-8859-1>
All Ruby script code has an associated Encoding
which any String
literal created in the source code will be associated to.
The default script encoding is Encoding::UTF_8 after v2.0, but it can be changed by a magic comment on the first line of the source code file (or second line, if there is a shebang line on the first). The comment must contain the word coding
or encoding
, followed by a colon, space and the Encoding
name or alias:
# encoding: UTF-8 "some string".encoding #=> #<Encoding:UTF-8>
The __ENCODING__
keyword returns the script encoding of the file which the keyword is written:
# encoding: ISO-8859-1 __ENCODING__ #=> #<Encoding:ISO-8859-1>
ruby -K
will change the default locale encoding, but this is not recommended. Ruby source files should declare its script encoding by a magic comment even when they only depend on US-ASCII strings or regular expressions.
The default encoding of the environment. Usually derived from locale.
see Encoding.locale_charmap
, Encoding.find
(‘locale’)
The default encoding of strings from the filesystem of the environment. This is used for strings of file names or paths.
see Encoding.find
(‘filesystem’)
Each IO
object has an external encoding which indicates the encoding that Ruby will use to read its data. By default Ruby sets the external encoding of an IO
object to the default external encoding. The default external encoding is set by locale encoding or the interpreter -E
option. Encoding.default_external
returns the current value of the external encoding.
ENV["LANG"] #=> "UTF-8" Encoding.default_external #=> #<Encoding:UTF-8> $ ruby -E ISO-8859-1 -e "p Encoding.default_external" #<Encoding:ISO-8859-1> $ LANG=C ruby -e 'p Encoding.default_external' #<Encoding:US-ASCII>
The default external encoding may also be set through Encoding.default_external=
, but you should not do this as strings created before and after the change will have inconsistent encodings. Instead use ruby -E
to invoke ruby with the correct external encoding.
When you know that the actual encoding of the data of an IO
object is not the default external encoding, you can reset its external encoding with IO#set_encoding
or set it at IO
object creation (see IO.new
options).
To process the data of an IO
object which has an encoding different from its external encoding, you can set its internal encoding. Ruby will use this internal encoding to transcode the data when it is read from the IO
object.
Conversely, when data is written to the IO
object it is transcoded from the internal encoding to the external encoding of the IO
object.
The internal encoding of an IO
object can be set with IO#set_encoding
or at IO
object creation (see IO.new
options).
The internal encoding is optional and when not set, the Ruby default internal encoding is used. If not explicitly set this default internal encoding is nil
meaning that by default, no transcoding occurs.
The default internal encoding can be set with the interpreter option -E
. Encoding.default_internal
returns the current internal encoding.
$ ruby -e 'p Encoding.default_internal' nil $ ruby -E ISO-8859-1:UTF-8 -e "p [Encoding.default_external, \ Encoding.default_internal]" [#<Encoding:ISO-8859-1>, #<Encoding:UTF-8>]
The default internal encoding may also be set through Encoding.default_internal=
, but you should not do this as strings created before and after the change will have inconsistent encodings. Instead use ruby -E
to invoke ruby with the correct internal encoding.
IO
encoding example In the following example a UTF-8 encoded string “Ru00E9sumu00E9” is transcoded for output to ISO-8859-1 encoding, then read back in and transcoded to UTF-8:
string = "R\u00E9sum\u00E9" open("transcoded.txt", "w:ISO-8859-1") do |io| io.write(string) end puts "raw text:" p File.binread("transcoded.txt") puts open("transcoded.txt", "r:ISO-8859-1:UTF-8") do |io| puts "transcoded text:" p io.read end
While writing the file, the internal encoding is not specified as it is only necessary for reading. While reading the file both the internal and external encoding must be specified to obtain the correct result.
$ ruby t.rb raw text: "R\xE9sum\xE9" transcoded text: "R\u00E9sum\u00E9"
Class Exception
and its subclasses are used to communicate between Kernel#raise
and rescue
statements in begin ... end
blocks.
An Exception
object carries information about an exception:
Its type (the exception’s class).
An optional descriptive message.
Optional backtrace information.
Some built-in subclasses of Exception
have additional methods: e.g., NameError#name
.
Two Ruby statements have default exception classes:
raise
: defaults to RuntimeError
.
rescue
: defaults to StandardError
.
When an exception has been raised but not yet handled (in rescue
, ensure
, at_exit
and END
blocks), two global variables are set:
$!
contains the current exception.
$@
contains its backtrace.
To provide additional or alternate information, a program may create custom exception classes that derive from the built-in exception classes.
A good practice is for a library to create a single “generic” exception class (typically a subclass of StandardError
or RuntimeError
) and have its other exception classes derive from that class. This allows the user to rescue the generic exception, thus catching all exceptions the library may raise even if future versions of the library add new exception subclasses.
For example:
class MyLibrary class Error < ::StandardError end class WidgetError < Error end class FrobError < Error end end
To handle both MyLibrary::WidgetError and MyLibrary::FrobError the library user can rescue MyLibrary::Error.
Exception
Classes The built-in subclasses of Exception
are:
fatal
Raised when a signal is received.
begin Process.kill('HUP',Process.pid) sleep # wait for receiver to handle signal sent by Process.kill rescue SignalException => e puts "received Exception #{e}" end
produces:
received Exception SIGHUP
The most standard error types are subclasses of StandardError
. A rescue clause without an explicit Exception
class will rescue all StandardErrors (and only those).
def foo raise "Oups" end foo rescue "Hello" #=> "Hello"
On the other hand:
require 'does/not/exist' rescue "Hi"
raises the exception:
LoadError: no such file to load -- does/not/exist
EncodingError
is the base class for encoding errors.
A rational number can be represented as a pair of integer numbers: a/b (b>0), where a is the numerator and b is the denominator. Integer
a equals rational a/1 mathematically.
You can create a Rational object explicitly with:
You can convert certain objects to Rationals with:
Method Rational.
Examples
Rational(1) #=> (1/1) Rational(2, 3) #=> (2/3) Rational(4, -6) #=> (-2/3) # Reduced. 3.to_r #=> (3/1) 2/3r #=> (2/3)
You can also create rational objects from floating-point numbers or strings.
Rational(0.3) #=> (5404319552844595/18014398509481984) Rational('0.3') #=> (3/10) Rational('2/3') #=> (2/3) 0.3.to_r #=> (5404319552844595/18014398509481984) '0.3'.to_r #=> (3/10) '2/3'.to_r #=> (2/3) 0.3.rationalize #=> (3/10)
A rational object is an exact number, which helps you to write programs without any rounding errors.
10.times.inject(0) {|t| t + 0.1 } #=> 0.9999999999999999 10.times.inject(0) {|t| t + Rational('0.1') } #=> (1/1)
However, when an expression includes an inexact component (numerical value or operation), it will produce an inexact result.
Rational(10) / 3 #=> (10/3) Rational(10) / 3.0 #=> 3.3333333333333335 Rational(-8) ** Rational(1, 3) #=> (1.0000000000000002+1.7320508075688772i)
Class Struct provides a convenient way to create a simple class that can store and fetch values.
This example creates a subclass of Struct
, Struct::Customer
; the first argument, a string, is the name of the subclass; the other arguments, symbols, determine the members of the new subclass.
Customer = Struct.new('Customer', :name, :address, :zip) Customer.name # => "Struct::Customer" Customer.class # => Class Customer.superclass # => Struct
Corresponding to each member are two methods, a writer and a reader, that store and fetch values:
methods = Customer.instance_methods false methods # => [:zip, :address=, :zip=, :address, :name, :name=]
An instance of the subclass may be created, and its members assigned values, via method ::new
:
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345) joe # => #<struct Struct::Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=12345>
The member values may be managed thus:
joe.name # => "Joe Smith" joe.name = 'Joseph Smith' joe.name # => "Joseph Smith"
And thus; note that member name may be expressed as either a string or a symbol:
joe[:name] # => "Joseph Smith" joe[:name] = 'Joseph Smith, Jr.' joe['name'] # => "Joseph Smith, Jr."
See Struct::new
.
First, what’s elsewhere. Class Struct:
Inherits from class Object.
Includes module Enumerable, which provides dozens of additional methods.
Here, class Struct provides methods that are useful for:
Struct
Subclass ::new
Returns a new subclass of Struct.
Returns whether a given object is equal to self
, using ==
to compare member values.
eql?
Returns whether a given object is equal to self
, using eql?
to compare member values.
[]
Returns the value associated with a given member name.
to_a
, values
, deconstruct
Returns the member values in self
as an array.
deconstruct_keys
Returns a hash of the name/value pairs for given member names.
dig
Returns the object in nested objects that is specified by a given member name and additional arguments.
members
Returns an array of the member names.
select
, filter
Returns an array of member values from self
, as selected by the given block.
values_at
Returns an array containing values for given member names.
[]=
Assigns a given value to a given member name.
each
Calls a given block with each member name.
each_pair
Calls a given block with each member name/value pair.