Results for: "pstore"

EncodingError is the base class for encoding errors.

No documentation available
No documentation available

An OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their accompanying values. This is accomplished by using Ruby’s metaprogramming to define methods on the class itself.

Examples

require "ostruct"

person = OpenStruct.new
person.name = "John Smith"
person.age  = 70

person.name      # => "John Smith"
person.age       # => 70
person.address   # => nil

An OpenStruct employs a Hash internally to store the attributes and values and can even be initialized with one:

australia = OpenStruct.new(:country => "Australia", :capital => "Canberra")
  # => #<OpenStruct country="Australia", capital="Canberra">

Hash keys with spaces or characters that could normally not be used for method calls (e.g. ()[]*) will not be immediately available on the OpenStruct object as a method for retrieval or assignment, but can still be reached through the Object#send method or using [].

measurements = OpenStruct.new("length (in inches)" => 24)
measurements[:"length (in inches)"]       # => 24
measurements.send("length (in inches)")   # => 24

message = OpenStruct.new(:queued? => true)
message.queued?                           # => true
message.send("queued?=", false)
message.queued?                           # => false

Removing the presence of an attribute requires the execution of the delete_field method as setting the property value to nil will not remove the attribute.

first_pet  = OpenStruct.new(:name => "Rowdy", :owner => "John Smith")
second_pet = OpenStruct.new(:name => "Rowdy")

first_pet.owner = nil
first_pet                 # => #<OpenStruct name="Rowdy", owner=nil>
first_pet == second_pet   # => false

first_pet.delete_field(:owner)
first_pet                 # => #<OpenStruct name="Rowdy">
first_pet == second_pet   # => true

Ractor compatibility: A frozen OpenStruct with shareable values is itself shareable.

Caveats

An OpenStruct utilizes Ruby’s method lookup structure to find and define the necessary methods for properties. This is accomplished through the methods method_missing and define_singleton_method.

This should be a consideration if there is a concern about the performance of the objects that are created, as there is much more overhead in the setting of these properties compared to using a Hash or a Struct. Creating an open struct from a small Hash and accessing a few of the entries can be 200 times slower than accessing the hash directly.

This is a potential security issue; building OpenStruct from untrusted user data (e.g. JSON web request) may be susceptible to a “symbol denial of service” attack since the keys create methods and names of methods are never garbage collected.

This may also be the source of incompatibilities between Ruby versions:

o = OpenStruct.new
o.then # => nil in Ruby < 2.6, enumerator for Ruby >= 2.6

Builtin methods may be overwritten this way, which may be a source of bugs or security issues:

o = OpenStruct.new
o.methods # => [:to_h, :marshal_load, :marshal_dump, :each_pair, ...
o.methods = [:foo, :bar]
o.methods # => [:foo, :bar]

To help remedy clashes, OpenStruct uses only protected/private methods ending with ! and defines aliases for builtin public methods by adding a !:

o = OpenStruct.new(make: 'Bentley', class: :luxury)
o.class # => :luxury
o.class! # => OpenStruct

It is recommended (but not enforced) to not use fields ending in !; Note that a subclass’ methods may not be overwritten, nor can OpenStruct’s own methods ending with !.

For all these reasons, consider not using OpenStruct at all.

A regular expression (also called a regexp) is a match pattern (also simply called a pattern).

A common notation for a regexp uses enclosing slash characters:

/foo/

A regexp may be applied to a target string; The part of the string (if any) that matches the pattern is called a match, and may be said to match:

re = /red/
re.match?('redirect') # => true   # Match at beginning of target.
re.match?('bored')    # => true   # Match at end of target.
re.match?('credit')   # => true   # Match within target.
re.match?('foo')      # => false  # No match.

Regexp Uses

A regexp may be used:

Regexp Objects

A regexp object has:

Creating a Regexp

A regular expression may be created with:

Method match

Each of the methods Regexp#match, String#match, and Symbol#match returns a MatchData object if a match was found, nil otherwise; each also sets global variables:

'food'.match(/foo/) # => #<MatchData "foo">
'food'.match(/bar/) # => nil

Operator =~

Each of the operators Regexp#=~, String#=~, and Symbol#=~ returns an integer offset if a match was found, nil otherwise; each also sets global variables:

/bar/ =~ 'foo bar' # => 4
'foo bar' =~ /bar/ # => 4
/baz/ =~ 'foo bar' # => nil

Method match?

Each of the methods Regexp#match?, String#match?, and Symbol#match? returns true if a match was found, false otherwise; none sets global variables:

'food'.match?(/foo/) # => true
'food'.match?(/bar/) # => false

Global Variables

Certain regexp-oriented methods assign values to global variables:

The affected global variables are:

Examples:

# Matched string, but no matched groups.
'foo bar bar baz'.match('bar')
$~ # => #<MatchData "bar">
$& # => "bar"
$` # => "foo "
$' # => " bar baz"
$+ # => nil
$1 # => nil

# Matched groups.
/s(\w{2}).*(c)/.match('haystack')
$~ # => #<MatchData "stac" 1:"ta" 2:"c">
$& # => "stac"
$` # => "hay"
$' # => "k"
$+ # => "c"
$1 # => "ta"
$2 # => "c"
$3 # => nil

# No match.
'foo'.match('bar')
$~ # => nil
$& # => nil
$` # => nil
$' # => nil
$+ # => nil
$1 # => nil

Note that Regexp#match?, String#match?, and Symbol#match? do not set global variables.

Sources

As seen above, the simplest regexp uses a literal expression as its source:

re = /foo/              # => /foo/
re.match('food')        # => #<MatchData "foo">
re.match('good')        # => nil

A rich collection of available subexpressions gives the regexp great power and flexibility:

Special Characters

Regexp special characters, called metacharacters, have special meanings in certain contexts; depending on the context, these are sometimes metacharacters:

. ? - + * ^ \ | $ ( ) [ ] { }

To match a metacharacter literally, backslash-escape it:

# Matches one or more 'o' characters.
/o+/.match('foo')  # => #<MatchData "oo">
# Would match 'o+'.
/o\+/.match('foo') # => nil

To match a backslash literally, backslash-escape it:

/\./.match('\.')  # => #<MatchData ".">
/\\./.match('\.') # => #<MatchData "\\.">

Method Regexp.escape returns an escaped string:

Regexp.escape('.?-+*^\|$()[]{}')
# => "\\.\\?\\-\\+\\*\\^\\\\\\|\\$\\(\\)\\[\\]\\{\\}"

Source Literals

The source literal largely behaves like a double-quoted string; see Regexp Literals.

In particular, a source literal may contain interpolated expressions:

s = 'foo'         # => "foo"
/#{s}/            # => /foo/
/#{s.capitalize}/ # => /Foo/
/#{2 + 2}/        # => /4/

There are differences between an ordinary string literal and a source literal; see Shorthand Character Classes.

Character Classes

A character class is delimited by square brackets; it specifies that certain characters match at a given point in the target string:

# This character class will match any vowel.
re = /B[aeiou]rd/
re.match('Bird') # => #<MatchData "Bird">
re.match('Bard') # => #<MatchData "Bard">
re.match('Byrd') # => nil

A character class may contain hyphen characters to specify ranges of characters:

# These regexps have the same effect.
/[abcdef]/.match('foo') # => #<MatchData "f">
/[a-f]/.match('foo')    # => #<MatchData "f">
/[a-cd-f]/.match('foo') # => #<MatchData "f">

When the first character of a character class is a caret (^), the sense of the class is inverted: it matches any character except those specified.

/[^a-eg-z]/.match('f') # => #<MatchData "f">

A character class may contain another character class. By itself this isn’t useful because [a-z[0-9]] describes the same set as [a-z0-9].

However, character classes also support the && operator, which performs set intersection on its arguments. The two can be combined as follows:

/[a-w&&[^c-g]z]/ # ([a-w] AND ([^c-g] OR z))

This is equivalent to:

/[abh-w]/

Shorthand Character Classes

Each of the following metacharacters serves as a shorthand for a character class:

Anchors

An anchor is a metasequence that matches a zero-width position between characters in the target string.

For a subexpression with no anchor, matching may begin anywhere in the target string:

/real/.match('surrealist') # => #<MatchData "real">

For a subexpression with an anchor, matching must begin at the matched anchor.

Boundary Anchors

Each of these anchors matches a boundary:

Lookaround Anchors

Lookahead anchors:

Lookbehind anchors:

The pattern below uses positive lookahead and positive lookbehind to match text appearing in tags without including the tags in the match:

/(?<=<b>)\w+(?=<\/b>)/.match("Fortune favors the <b>bold</b>.")
# => #<MatchData "bold">

Match-Reset Anchor

Alternation

The vertical bar metacharacter (|) may be used within parentheses to express alternation: two or more subexpressions any of which may match the target string.

Two alternatives:

re = /(a|b)/
re.match('foo') # => nil
re.match('bar') # => #<MatchData "b" 1:"b">

Four alternatives:

re = /(a|b|c|d)/
re.match('shazam') # => #<MatchData "a" 1:"a">
re.match('cold')   # => #<MatchData "c" 1:"c">

Each alternative is a subexpression, and may be composed of other subexpressions:

re = /([a-c]|[x-z])/
re.match('bar') # => #<MatchData "b" 1:"b">
re.match('ooz') # => #<MatchData "z" 1:"z">

Method Regexp.union provides a convenient way to construct a regexp with alternatives.

Quantifiers

A simple regexp matches one character:

/\w/.match('Hello')  # => #<MatchData "H">

An added quantifier specifies how many matches are required or allowed:

Greedy, Lazy, or Possessive Matching

Quantifier matching may be greedy, lazy, or possessive:

More:

Groups and Captures

A simple regexp has (at most) one match:

re = /\d\d\d\d-\d\d-\d\d/
re.match('1943-02-04')      # => #<MatchData "1943-02-04">
re.match('1943-02-04').size # => 1
re.match('foo')             # => nil

Adding one or more pairs of parentheses, (subexpression), defines groups, which may result in multiple matched substrings, called captures:

re = /(\d\d\d\d)-(\d\d)-(\d\d)/
re.match('1943-02-04')      # => #<MatchData "1943-02-04" 1:"1943" 2:"02" 3:"04">
re.match('1943-02-04').size # => 4

The first capture is the entire matched string; the other captures are the matched substrings from the groups.

A group may have a quantifier:

re = /July 4(th)?/
re.match('July 4')   # => #<MatchData "July 4" 1:nil>
re.match('July 4th') # => #<MatchData "July 4th" 1:"th">

re = /(foo)*/
re.match('')       # => #<MatchData "" 1:nil>
re.match('foo')    # => #<MatchData "foo" 1:"foo">
re.match('foofoo') # => #<MatchData "foofoo" 1:"foo">

re = /(foo)+/
re.match('')       # => nil
re.match('foo')    # => #<MatchData "foo" 1:"foo">
re.match('foofoo') # => #<MatchData "foofoo" 1:"foo">

The returned MatchData object gives access to the matched substrings:

re = /(\d\d\d\d)-(\d\d)-(\d\d)/
md = re.match('1943-02-04')
# => #<MatchData "1943-02-04" 1:"1943" 2:"02" 3:"04">
md[0] # => "1943-02-04"
md[1] # => "1943"
md[2] # => "02"
md[3] # => "04"

Non-Capturing Groups

A group may be made non-capturing; it is still a group (and, for example, can have a quantifier), but its matching substring is not included among the captures.

A non-capturing group begins with ?: (inside the parentheses):

# Don't capture the year.
re = /(?:\d\d\d\d)-(\d\d)-(\d\d)/
md = re.match('1943-02-04') # => #<MatchData "1943-02-04" 1:"02" 2:"04">

Backreferences

A group match may also be referenced within the regexp itself; such a reference is called a backreference:

/[csh](..) [csh]\1 in/.match('The cat sat in the hat')
# => #<MatchData "cat sat in" 1:"at">

This table shows how each subexpression in the regexp above matches a substring in the target string:

| Subexpression in Regexp   | Matching Substring in Target String |
|---------------------------|-------------------------------------|
|       First '[csh]'       |            Character 'c'            |
|          '(..)'           |        First substring 'at'         |
|      First space ' '      |      First space character ' '      |
|       Second '[csh]'      |            Character 's'            |
| '\1' (backreference 'at') |        Second substring 'at'        |
|           ' in'           |            Substring ' in'          |

A regexp may contain any number of groups:

Named Captures

As seen above, a capture can be referred to by its number. A capture can also have a name, prefixed as ?<name> or ?'name', and the name (symbolized) may be used as an index in MatchData[]:

md = /\$(?<dollars>\d+)\.(?'cents'\d+)/.match("$3.67")
# => #<MatchData "$3.67" dollars:"3" cents:"67">
md[:dollars]  # => "3"
md[:cents]    # => "67"
# The capture numbers are still valid.
md[2]         # => "67"

When a regexp contains a named capture, there are no unnamed captures:

/\$(?<dollars>\d+)\.(\d+)/.match("$3.67")
# => #<MatchData "$3.67" dollars:"3">

A named group may be backreferenced as \k<name>:

/(?<vowel>[aeiou]).\k<vowel>.\k<vowel>/.match('ototomy')
# => #<MatchData "ototo" vowel:"o">

When (and only when) a regexp contains named capture groups and appears before the =~ operator, the captured substrings are assigned to local variables with corresponding names:

/\$(?<dollars>\d+)\.(?<cents>\d+)/ =~ '$3.67'
dollars # => "3"
cents   # => "67"

Method Regexp#named_captures returns a hash of the capture names and substrings; method Regexp#names returns an array of the capture names.

Atomic Grouping

A group may be made atomic with (?>subexpression).

This causes the subexpression to be matched independently of the rest of the expression, so that the matched substring becomes fixed for the remainder of the match, unless the entire subexpression must be abandoned and subsequently revisited.

In this way subexpression is treated as a non-divisible whole. Atomic grouping is typically used to optimise patterns to prevent needless backtracking .

Example (without atomic grouping):

/".*"/.match('"Quote"') # => #<MatchData "\"Quote\"">

Analysis:

  1. The leading subexpression " in the pattern matches the first character " in the target string.

  2. The next subexpression .* matches the next substring Quote“ (including the trailing double-quote).

  3. Now there is nothing left in the target string to match the trailing subexpression " in the pattern; this would cause the overall match to fail.

  4. The matched substring is backtracked by one position: Quote.

  5. The final subexpression " now matches the final substring ", and the overall match succeeds.

If subexpression .* is grouped atomically, the backtracking is disabled, and the overall match fails:

/"(?>.*)"/.match('"Quote"') # => nil

Atomic grouping can affect performance; see Atomic Group.

Subexpression Calls

As seen above, a backreference number (\n) or name (\k<name>) gives access to a captured substring; the corresponding regexp subexpression may also be accessed, via the number (\gn) or name (\g<name>):

/\A(?<paren>\(\g<paren>*\))*\z/.match('(())')
# ^1
#      ^2
#           ^3
#                 ^4
#      ^5
#           ^6
#                      ^7
#                       ^8
#                       ^9
#                           ^10

The pattern:

  1. Matches at the beginning of the string, i.e. before the first character.

  2. Enters a named group paren.

  3. Matches the first character in the string, '('.

  4. Calls the paren group again, i.e. recurses back to the second step.

  5. Re-enters the paren group.

  6. Matches the second character in the string, '('.

  7. Attempts to call paren a third time, but fails because doing so would prevent an overall successful match.

  8. Matches the third character in the string, ')'; marks the end of the second recursive call

  9. Matches the fourth character in the string, ')'.

  10. Matches the end of the string.

See Subexpression calls.

Conditionals

The conditional construct takes the form (?(cond)yes|no), where:

Examples:

re = /\A(foo)?(?(1)(T)|(F))\z/
re.match('fooT') # => #<MatchData "fooT" 1:"foo" 2:"T" 3:nil>
re.match('F')    # => #<MatchData "F" 1:nil 2:nil 3:"F">
re.match('fooF') # => nil
re.match('T')    # => nil

re = /\A(?<xyzzy>foo)?(?(<xyzzy>)(T)|(F))\z/
re.match('fooT') # => #<MatchData "fooT" xyzzy:"foo">
re.match('F')    # => #<MatchData "F" xyzzy:nil>
re.match('fooF') # => nil
re.match('T')    # => nil

Absence Operator

The absence operator is a special group that matches anything which does not match the contained subexpressions.

/(?~real)/.match('surrealist') # => #<MatchData "surrea">
/(?~real)ist/.match('surrealist') # => #<MatchData "ealist">
/sur(?~real)ist/.match('surrealist') # => nil

Unicode

Unicode Properties

The /\p{property_name}/ construct (with lowercase p) matches characters using a Unicode property name, much like a character class; property Alpha specifies alphabetic characters:

/\p{Alpha}/.match('a') # => #<MatchData "a">
/\p{Alpha}/.match('1') # => nil

A property can be inverted by prefixing the name with a caret character (^):

/\p{^Alpha}/.match('1') # => #<MatchData "1">
/\p{^Alpha}/.match('a') # => nil

Or by using \P (uppercase P):

/\P{Alpha}/.match('1') # => #<MatchData "1">
/\P{Alpha}/.match('a') # => nil

See Unicode Properties for regexps based on the numerous properties.

Some commonly-used properties correspond to POSIX bracket expressions:

These are also commonly used:

Unicode Character Categories

A Unicode character category name:

Examples:

/\p{lu}/                # => /\p{lu}/
/\p{LU}/                # => /\p{LU}/
/\p{Uppercase Letter}/  # => /\p{Uppercase Letter}/
/\p{Uppercase_Letter}/  # => /\p{Uppercase_Letter}/
/\p{UPPERCASE-LETTER}/  # => /\p{UPPERCASE-LETTER}/

Below are the Unicode character category abbreviations and names. Enumerations of characters in each category are at the links.

Letters:

Marks:

Numbers:

Punctation:

Unicode Scripts and Blocks

Among the Unicode properties are:

POSIX Bracket Expressions

A POSIX bracket expression is also similar to a character class. These expressions provide a portable alternative to the above, with the added benefit of encompassing non-ASCII characters:

The POSIX bracket expressions:

Ruby also supports these (non-POSIX) bracket expressions:

Comments

A comment may be included in a regexp pattern using the (?#comment) construct, where comment is a substring that is to be ignored. arbitrary text ignored by the regexp engine:

/foo(?#Ignore me)bar/.match('foobar') # => #<MatchData "foobar">

The comment may not include an unescaped terminator character.

See also Extended Mode.

Modes

Each of these modifiers sets a mode for the regexp:

Any, all, or none of these may be applied.

Modifiers i, m, and x may be applied to subexpressions:

Example:

re = /(?i)te(?-i)st/
re.match('test') # => #<MatchData "test">
re.match('TEst') # => #<MatchData "TEst">
re.match('TEST') # => nil
re.match('teST') # => nil

re = /t(?i:e)st/
re.match('test') # => #<MatchData "test">
re.match('tEst') # => #<MatchData "tEst">
re.match('tEST') # => nil

Method Regexp#options returns an integer whose value showing the settings for case-insensitivity mode, multiline mode, and extended mode.

Case-Insensitive Mode

By default, a regexp is case-sensitive:

/foo/.match('FOO')  # => nil

Modifier i enables case-insensitive mode:

/foo/i.match('FOO')
# => #<MatchData "FOO">

Method Regexp#casefold? returns whether the mode is case-insensitive.

Multiline Mode

The multiline-mode in Ruby is what is commonly called a “dot-all mode”:

Unlike other languages, the modifier m does not affect the anchors ^ and $. These anchors always match at line-boundaries in Ruby.

Extended Mode

Modifier x enables extended mode, which means that:

In extended mode, whitespace and comments may be used to form a self-documented regexp.

Regexp not in extended mode (matches some Roman numerals):

pattern = '^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$'
re = /#{pattern}/
re.match('MCMXLIII') # => #<MatchData "MCMXLIII" 1:"CM" 2:"XL" 3:"III">

Regexp in extended mode:

pattern = <<-EOT
  ^                   # beginning of string
  M{0,3}              # thousands - 0 to 3 Ms
  (CM|CD|D?C{0,3})    # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 Cs),
                      #            or 500-800 (D, followed by 0 to 3 Cs)
  (XC|XL|L?X{0,3})    # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 Xs),
                      #        or 50-80 (L, followed by 0 to 3 Xs)
  (IX|IV|V?I{0,3})    # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 Is),
                      #        or 5-8 (V, followed by 0 to 3 Is)
  $                   # end of string
EOT
re = /#{pattern}/x
re.match('MCMXLIII') # => #<MatchData "MCMXLIII" 1:"CM" 2:"XL" 3:"III">

Interpolation Mode

Modifier o means that the first time a literal regexp with interpolations is encountered, the generated Regexp object is saved and used for all future evaluations of that literal regexp. Without modifier o, the generated Regexp is not saved, so each evaluation of the literal regexp generates a new Regexp object.

Without modifier o:

def letters; sleep 5; /[A-Z][a-z]/; end
words = %w[abc def xyz]
start = Time.now
words.each {|word| word.match(/\A[#{letters}]+\z/) }
Time.now - start # => 15.0174892

With modifier o:

start = Time.now
words.each {|word| word.match(/\A[#{letters}]+\z/o) }
Time.now - start # => 5.0010866

Note that if the literal regexp does not have interpolations, the o behavior is the default.

Encodings

By default, a regexp with only US-ASCII characters has US-ASCII encoding:

re = /foo/
re.source.encoding # => #<Encoding:US-ASCII>
re.encoding        # => #<Encoding:US-ASCII>

A regular expression containing non-US-ASCII characters is assumed to use the source encoding. This can be overridden with one of the following modifiers.

A regexp can be matched against a target string when either:

If a match between incompatible encodings is attempted an Encoding::CompatibilityError exception is raised.

Example:

re = eval("# encoding: ISO-8859-1\n/foo\\xff?/")
re.encoding                 # => #<Encoding:ISO-8859-1>
re =~ "foo".encode("UTF-8") # => 0
re =~ "foo\u0100"           # Raises Encoding::CompatibilityError

The encoding may be explicitly fixed by including Regexp::FIXEDENCODING in the second argument for Regexp.new:

# Regexp with encoding ISO-8859-1.
re = Regexp.new("a".force_encoding('iso-8859-1'), Regexp::FIXEDENCODING)
re.encoding  # => #<Encoding:ISO-8859-1>
# Target string with encoding UTF-8.
s = "a\u3042"
s.encoding   # => #<Encoding:UTF-8>
re.match(s)  # Raises Encoding::CompatibilityError.

Timeouts

When either a regexp source or a target string comes from untrusted input, malicious values could become a denial-of-service attack; to prevent such an attack, it is wise to set a timeout.

Regexp has two timeout values:

When regexp.timeout is nil, the timeout “falls through” to Regexp.timeout; when regexp.timeout is non-nil, that value controls timing out:

| regexp.timeout Value | Regexp.timeout Value |            Result           |
|----------------------|----------------------|-----------------------------|
|         nil          |          nil         |       Never times out.      |
|         nil          |         Float        | Times out in Float seconds. |
|        Float         |          Any         | Times out in Float seconds. |

Optimization

For certain values of the pattern and target string, matching time can grow polynomially or exponentially in relation to the input size; the potential vulnerability arising from this is the regular expression denial-of-service (ReDoS) attack.

Regexp matching can apply an optimization to prevent ReDoS attacks. When the optimization is applied, matching time increases linearly (not polynomially or exponentially) in relation to the input size, and a ReDoS attach is not possible.

This optimization is applied if the pattern meets these criteria:

You can use method Regexp.linear_time? to determine whether a pattern meets these criteria:

Regexp.linear_time?(/a*/)     # => true
Regexp.linear_time?('a*')     # => true
Regexp.linear_time?(/(a*)\1/) # => false

However, an untrusted source may not be safe even if the method returns true, because the optimization uses memoization (which may invoke large memory consumption).

References

Read (online PDF books):

Explore, test (interactive online editor):

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.

What’s Here

First, what’s elsewhere. Class Struct:

See also Data, which is a somewhat similar, but stricter concept for defining immutable value objects.

Here, class Struct provides methods that are useful for:

Methods for Creating a Struct Subclass

Methods for Querying

Methods for Comparing

Methods for Fetching

Methods for Assigning

Methods for Iterating

Methods for Converting

SocketError is the error class for socket.

IPSocket is the super class of TCPSocket and UDPSocket.

UDPSocket represents a UDP/IP socket.

TCPServer represents a TCP/IP server socket.

A simple TCP server may look like:

require 'socket'

server = TCPServer.new 2000 # Server bind to port 2000
loop do
  client = server.accept    # Wait for a client to connect
  client.puts "Hello !"
  client.puts "Time is #{Time.now}"
  client.close
end

A more usable server (serving multiple clients):

require 'socket'

server = TCPServer.new 2000
loop do
  Thread.start(server.accept) do |client|
    client.puts "Hello !"
    client.puts "Time is #{Time.now}"
    client.close
  end
end

TCPSocket represents a TCP/IP client socket.

A simple client may look like:

require 'socket'

s = TCPSocket.new 'localhost', 2000

while line = s.gets # Read lines from socket
  puts line         # and print them
end

s.close             # close socket when done

IO streams for strings, with access similar to IO; see IO.

About the Examples

Examples on this page assume that StringIO has been required:

require 'stringio'

StringScanner provides for lexical scanning operations on a String. Here is an example of its usage:

require 'strscan'

s = StringScanner.new('This is an example string')
s.eos?               # -> false

p s.scan(/\w+/)      # -> "This"
p s.scan(/\w+/)      # -> nil
p s.scan(/\s+/)      # -> " "
p s.scan(/\s+/)      # -> nil
p s.scan(/\w+/)      # -> "is"
s.eos?               # -> false

p s.scan(/\s+/)      # -> " "
p s.scan(/\w+/)      # -> "an"
p s.scan(/\s+/)      # -> " "
p s.scan(/\w+/)      # -> "example"
p s.scan(/\s+/)      # -> " "
p s.scan(/\w+/)      # -> "string"
s.eos?               # -> true

p s.scan(/\s+/)      # -> nil
p s.scan(/\w+/)      # -> nil

Scanning a string means remembering the position of a scan pointer, which is just an index. The point of scanning is to move forward a bit at a time, so matches are sought after the scan pointer; usually immediately after it.

Given the string “test string”, here are the pertinent scan pointer positions:

  t e s t   s t r i n g
0 1 2 ...             1
                      0

When you scan for a pattern (a regular expression), the match must occur at the character after the scan pointer. If you use scan_until, then the match can occur anywhere after the scan pointer. In both cases, the scan pointer moves just beyond the last character of the match, ready to scan again from the next character onwards. This is demonstrated by the example above.

Method Categories

There are other methods besides the plain scanners. You can look ahead in the string without actually scanning. You can access the most recent match. You can modify the string being scanned, reset or terminate the scanner, find out or change the position of the scan pointer, skip ahead, and so on.

Advancing the Scan Pointer

Looking Ahead

Finding Where we Are

Setting Where we Are

Match Data

Miscellaneous

There are aliases to several of the methods.

Windows NT

Raised when OLE processing failed.

EX:

obj = WIN32OLE.new("NonExistProgID")

raises the exception:

WIN32OLERuntimeError: unknown OLE server: `NonExistProgID'
    HRESULT error code:0x800401f3
      Invalid class string
No documentation available

Raised when an IO operation fails.

File.open("/etc/hosts") {|f| f << "example"}
  #=> IOError: not opened for writing

File.open("/etc/hosts") {|f| f.close; f.read }
  #=> IOError: closed stream

Note that some IO failures raise SystemCallErrors and these are not subclasses of IOError:

File.open("does/not/exist")
  #=> Errno::ENOENT: No such file or directory - does/not/exist

Raised by some IO operations when reaching the end of file. Many IO methods exist in two forms,

one that returns nil when the end of file is reached, the other raises EOFError.

EOFError is a subclass of IOError.

file = File.open("/etc/hosts")
file.read
file.gets     #=> nil
file.readline #=> EOFError: end of file reached
file.close

Class GetoptLong provides parsing both for options and for regular arguments.

Using GetoptLong, you can define options for your program. The program can then capture and respond to whatever options are included in the command that executes the program.

A simple example: file simple.rb:

require 'getoptlong'

options = GetoptLong.new(
  ['--number', '-n', GetoptLong::REQUIRED_ARGUMENT],
  ['--verbose', '-v', GetoptLong::OPTIONAL_ARGUMENT],
  ['--help', '-h', GetoptLong::NO_ARGUMENT]
)

If you are somewhat familiar with options, you may want to skip to this full example.

Options

A GetoptLong option has:

Options may be defined by calling singleton method GetoptLong.new, which returns a new GetoptLong object. Options may then be processed by calling other methods such as GetoptLong#each.

Option Name and Aliases

In the array that defines an option, the first element is the string option name. Often the name takes the ‘long’ form, beginning with two hyphens.

The option name may have any number of aliases, which are defined by additional string elements.

The name and each alias must be of one of two forms:

File aliases.rb:

require 'getoptlong'

options = GetoptLong.new(
  ['--xxx', '-x', '--aaa', '-a', '-p', GetoptLong::NO_ARGUMENT]
)
options.each do |option, argument|
  p [option, argument]
end

An option may be cited by its name, or by any of its aliases; the parsed option always reports the name, not an alias:

$ ruby aliases.rb -a -p --xxx --aaa -x

Output:

["--xxx", ""]
["--xxx", ""]
["--xxx", ""]
["--xxx", ""]
["--xxx", ""]

An option may also be cited by an abbreviation of its name or any alias, as long as that abbreviation is unique among the options.

File abbrev.rb:

require 'getoptlong'

options = GetoptLong.new(
  ['--xxx', GetoptLong::NO_ARGUMENT],
  ['--xyz', GetoptLong::NO_ARGUMENT]
)
options.each do |option, argument|
  p [option, argument]
end

Command line:

$ ruby abbrev.rb --xxx --xx --xyz --xy

Output:

["--xxx", ""]
["--xxx", ""]
["--xyz", ""]
["--xyz", ""]

This command line raises GetoptLong::AmbiguousOption:

$ ruby abbrev.rb --x

Repetition

An option may be cited more than once:

$ ruby abbrev.rb --xxx --xyz --xxx --xyz

Output:

["--xxx", ""]
["--xyz", ""]
["--xxx", ""]
["--xyz", ""]

Treating Remaining Options as Arguments

A option-like token that appears anywhere after the token -- is treated as an ordinary argument, and is not processed as an option:

$ ruby abbrev.rb --xxx --xyz -- --xxx --xyz

Output:

["--xxx", ""]
["--xyz", ""]

Option Types

Each option definition includes an option type, which controls whether the option takes an argument.

File types.rb:

require 'getoptlong'

options = GetoptLong.new(
  ['--xxx', GetoptLong::REQUIRED_ARGUMENT],
  ['--yyy', GetoptLong::OPTIONAL_ARGUMENT],
  ['--zzz', GetoptLong::NO_ARGUMENT]
)
options.each do |option, argument|
  p [option, argument]
end

Note that an option type has to do with the option argument (whether it is required, optional, or forbidden), not with whether the option itself is required.

Option with Required Argument

An option of type GetoptLong::REQUIRED_ARGUMENT must be followed by an argument, which is associated with that option:

$ ruby types.rb --xxx foo

Output:

["--xxx", "foo"]

If the option is not last, its argument is whatever follows it (even if the argument looks like another option):

$ ruby types.rb --xxx --yyy

Output:

["--xxx", "--yyy"]

If the option is last, an exception is raised:

$ ruby types.rb
# Raises GetoptLong::MissingArgument

Option with Optional Argument

An option of type GetoptLong::OPTIONAL_ARGUMENT may be followed by an argument, which if given is associated with that option.

If the option is last, it does not have an argument:

$ ruby types.rb --yyy

Output:

["--yyy", ""]

If the option is followed by another option, it does not have an argument:

$ ruby types.rb --yyy --zzz

Output:

["--yyy", ""]
["--zzz", ""]

Otherwise the option is followed by its argument, which is associated with that option:

$ ruby types.rb --yyy foo

Output:

["--yyy", "foo"]

Option with No Argument

An option of type GetoptLong::NO_ARGUMENT takes no argument:

ruby types.rb --zzz foo

Output:

["--zzz", ""]

ARGV

You can process options either with method each and a block, or with method get.

During processing, each found option is removed, along with its argument if there is one. After processing, each remaining element was neither an option nor the argument for an option.

File argv.rb:

require 'getoptlong'

options = GetoptLong.new(
  ['--xxx', GetoptLong::REQUIRED_ARGUMENT],
  ['--yyy', GetoptLong::OPTIONAL_ARGUMENT],
  ['--zzz', GetoptLong::NO_ARGUMENT]
)
puts "Original ARGV: #{ARGV}"
options.each do |option, argument|
  p [option, argument]
end
puts "Remaining ARGV: #{ARGV}"

Command line:

$ ruby argv.rb --xxx Foo --yyy Bar Baz --zzz Bat Bam

Output:

Original ARGV: ["--xxx", "Foo", "--yyy", "Bar", "Baz", "--zzz", "Bat", "Bam"]
["--xxx", "Foo"]
["--yyy", "Bar"]
["--zzz", ""]
Remaining ARGV: ["Baz", "Bat", "Bam"]

Ordering

There are three settings that control the way the options are interpreted:

The initial setting for a new GetoptLong object is REQUIRE_ORDER if environment variable POSIXLY_CORRECT is defined, PERMUTE otherwise.

PERMUTE Ordering

In the PERMUTE ordering, options and other, non-option, arguments may appear in any order and any mixture.

File permute.rb:

require 'getoptlong'

options = GetoptLong.new(
  ['--xxx', GetoptLong::REQUIRED_ARGUMENT],
  ['--yyy', GetoptLong::OPTIONAL_ARGUMENT],
  ['--zzz', GetoptLong::NO_ARGUMENT]
)
puts "Original ARGV: #{ARGV}"
options.each do |option, argument|
  p [option, argument]
end
puts "Remaining ARGV: #{ARGV}"

Command line:

$ ruby permute.rb Foo --zzz Bar --xxx Baz --yyy Bat Bam --xxx Bag Bah

Output:

Original ARGV: ["Foo", "--zzz", "Bar", "--xxx", "Baz", "--yyy", "Bat", "Bam", "--xxx", "Bag", "Bah"]
["--zzz", ""]
["--xxx", "Baz"]
["--yyy", "Bat"]
["--xxx", "Bag"]
Remaining ARGV: ["Foo", "Bar", "Bam", "Bah"]

REQUIRE_ORDER Ordering

In the REQUIRE_ORDER ordering, all options precede all non-options; that is, each word after the first non-option word is treated as a non-option word (even if it begins with a hyphen).

File require_order.rb:

require 'getoptlong'

options = GetoptLong.new(
  ['--xxx', GetoptLong::REQUIRED_ARGUMENT],
  ['--yyy', GetoptLong::OPTIONAL_ARGUMENT],
  ['--zzz', GetoptLong::NO_ARGUMENT]
)
options.ordering = GetoptLong::REQUIRE_ORDER
puts "Original ARGV: #{ARGV}"
options.each do |option, argument|
  p [option, argument]
end
puts "Remaining ARGV: #{ARGV}"

Command line:

$ ruby require_order.rb --xxx Foo Bar --xxx Baz --yyy Bat -zzz

Output:

Original ARGV: ["--xxx", "Foo", "Bar", "--xxx", "Baz", "--yyy", "Bat", "-zzz"]
["--xxx", "Foo"]
Remaining ARGV: ["Bar", "--xxx", "Baz", "--yyy", "Bat", "-zzz"]

RETURN_IN_ORDER Ordering

In the RETURN_IN_ORDER ordering, every word is treated as an option. A word that begins with a hyphen (or two) is treated in the usual way; a word word that does not so begin is treated as an option whose name is an empty string, and whose value is word.

File return_in_order.rb:

require 'getoptlong'

options = GetoptLong.new(
  ['--xxx', GetoptLong::REQUIRED_ARGUMENT],
  ['--yyy', GetoptLong::OPTIONAL_ARGUMENT],
  ['--zzz', GetoptLong::NO_ARGUMENT]
)
options.ordering = GetoptLong::RETURN_IN_ORDER
puts "Original ARGV: #{ARGV}"
options.each do |option, argument|
  p [option, argument]
end
puts "Remaining ARGV: #{ARGV}"

Command line:

$ ruby return_in_order.rb Foo --xxx Bar Baz --zzz Bat Bam

Output:

Original ARGV: ["Foo", "--xxx", "Bar", "Baz", "--zzz", "Bat", "Bam"]
["", "Foo"]
["--xxx", "Bar"]
["", "Baz"]
["--zzz", ""]
["", "Bat"]
["", "Bam"]
Remaining ARGV: []

Full Example

File fibonacci.rb:

require 'getoptlong'

options = GetoptLong.new(
  ['--number', '-n', GetoptLong::REQUIRED_ARGUMENT],
  ['--verbose', '-v', GetoptLong::OPTIONAL_ARGUMENT],
  ['--help', '-h', GetoptLong::NO_ARGUMENT]
)

def help(status = 0)
  puts <<~HELP
    Usage:

      -n n, --number n:
        Compute Fibonacci number for n.
      -v [boolean], --verbose [boolean]:
        Show intermediate results; default is 'false'.
      -h, --help:
        Show this help.
  HELP
  exit(status)
end

def print_fibonacci (number)
  return 0 if number == 0
  return 1 if number == 1 or number == 2
  i = 0
  j = 1
  (2..number).each do
    k = i + j
    i = j
    j = k
    puts j if @verbose
  end
  puts j unless @verbose
end

options.each do |option, argument|
  case option
  when '--number'
    @number = argument.to_i
  when '--verbose'
    @verbose = if argument.empty?
      true
    elsif argument.match(/true/i)
      true
    elsif argument.match(/false/i)
      false
    else
      puts '--verbose argument must be true or false'
      help(255)
    end
  when '--help'
    help
  end
end

unless @number
  puts 'Option --number is required.'
  help(255)
end

print_fibonacci(@number)

Command line:

$ ruby fibonacci.rb

Output:

Option --number is required.
Usage:

  -n n, --number n:
    Compute Fibonacci number for n.
  -v [boolean], --verbose [boolean]:
    Show intermediate results; default is 'false'.
  -h, --help:
    Show this help.

Command line:

$ ruby fibonacci.rb --number

Raises GetoptLong::MissingArgument:

fibonacci.rb: option `--number' requires an argument

Command line:

$ ruby fibonacci.rb --number 6

Output:

8

Command line:

$ ruby fibonacci.rb --number 6 --verbose

Output:

1
2
3
5
8

Command line:

$ ruby fibonacci.rb --number 6 --verbose yes

Output:

--verbose argument must be true or false
Usage:

  -n n, --number n:
    Compute Fibonacci number for n.
  -v [boolean], --verbose [boolean]:
    Show intermediate results; default is 'false'.
  -h, --help:
    Show this help.

This class implements a pretty printing algorithm. It finds line breaks and nice indentations for grouped structure.

By default, the class assumes that primitive elements are strings and each byte in the strings have single column in width. But it can be used for other situations by giving suitable arguments for some methods:

There are several candidate uses:

Bugs

Report any bugs at bugs.ruby-lang.org

References

Christian Lindig, Strictly Pretty, March 2000, lindig.github.io/papers/strictly-pretty-2000.pdf

Philip Wadler, A prettier printer, March 1998, homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier

Author

Tanaka Akira <akr@fsij.org>

Resolv is a thread-aware DNS resolver library written in Ruby. Resolv can handle multiple DNS requests concurrently without blocking the entire Ruby interpreter.

See also resolv-replace.rb to replace the libc resolver with Resolv.

Resolv can look up various DNS resources using the DNS module directly.

Examples:

p Resolv.getaddress "www.ruby-lang.org"
p Resolv.getname "210.251.121.214"

Resolv::DNS.open do |dns|
  ress = dns.getresources "www.ruby-lang.org", Resolv::DNS::Resource::IN::A
  p ress.map(&:address)
  ress = dns.getresources "ruby-lang.org", Resolv::DNS::Resource::IN::MX
  p ress.map { |r| [r.exchange.to_s, r.preference] }
end

Bugs

Weak Reference class that allows a referenced object to be garbage-collected.

A WeakRef may be used exactly like the object it references.

Usage:

foo = Object.new            # create a new object instance
p foo.to_s                  # original's class
foo = WeakRef.new(foo)      # reassign foo with WeakRef instance
p foo.to_s                  # should be same class
GC.start                    # start the garbage collector
p foo.to_s                  # should raise exception (recycled)

Raised when attempting to divide an integer by 0.

42 / 0   #=> ZeroDivisionError: divided by 0

Note that only division by an exact 0 will raise the exception:

42 /  0.0   #=> Float::INFINITY
42 / -0.0   #=> -Float::INFINITY
0  /  0.0   #=> NaN

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

Raised when Ruby can’t yield as requested.

A typical scenario is attempting to yield when no block is given:

def call_block
  yield 42
end
call_block

raises the exception:

LocalJumpError: no block given (yield)

A more subtle example:

def get_me_a_return
  Proc.new { return 42 }
end
get_me_a_return.call

raises the exception:

LocalJumpError: unexpected return
Search took: 3ms  ·  Total Results: 3855