Block Supersedes Default Value Argument Essay

1. Introduction

The value definition field of each CSS property can contain keywords, data types (which appear between < and >), and information on how they can be combined. Generic data types (<length> being the most widely used) that can be used by many properties are described in this specification, while more specific data types (e.g., <spacing-limit>) are described in the corresponding modules.

1.1. Module Interactions

This module replaces and extends the data type definitions in [CSS21] sections 1.4.2.1, 4.3, and A.2.

2. Value Definition Syntax

The syntax described here is used to define the set of valid values for CSS properties. A property value can have one or more components.

2.1. Component value types

Component value types are designated in several ways:

  1. keyword values (such as auto, disc, etc.), which appear literally, without quotes (e.g. )
  2. basic data types, which appear between < and > (e.g., <length>, <percentage>, etc.).
  3. types that have the same range of values as a property bearing the same name (e.g., <‘border-width’>, <‘background-attachment’>, etc.). In this case, the type name is the property name (complete with quotes) between the brackets. Such a type does not include CSS-wide keywords such as inherit.
  4. non-terminals that do not share the same name as a property. In this case, the non-terminal name appears between < and >, as in <spacing-limit>. Notice the distinction between <border-width> and <‘border-width’>: the latter is defined as the value of the border-width property, the former requires an explicit expansion elsewhere. The definition of a non-terminal is typically located near its first appearance in the specification.

Some property value definitions also include the slash (/), the comma (,), and/or parentheses as literals. These represent their corresponding tokens. Other non-keyword literal characters that may appear in a component value, such as “+”, must be written enclosed in single quotes.

specified in the grammar are implicitly omissible in some circumstances, when used to separate optional terms in the grammar. Within a top-level list in a property or other CSS value, or a function’s argument list, a comma specified in the grammar must be omitted if:

  • all items preceding the comma have been omitted
  • all items following the comma have been omitted
  • multiple commas would be adjacent (ignoring white space/comments), due to the items between the commas being omitted.
For example, if a function can accept three arguments in order, but all of them are optional, the grammar can be written like: example( first?, second?, third? )

Given this grammar, writing example(first, second, third) is valid, as is example(first, second) or example(first, third) or example(second). However, example(first, , third) is invalid, as one of those commas are no longer separating two options; similarly, example(,second) and example(first,) are invalid. example(first second) is also invalid, as commas are still required to actually separate the options.

If commas were not implicitly omittable, the grammar would have to be much more complicated to properly express the ways that the arguments can be omitted, greatly obscuring the simplicity of the feature.

All CSS properties also accept the CSS-wide keyword values as the sole component of their property value. For readability these are not listed explicitly in the property value syntax definitions. For example, the full value definition of border-color is (even though it is listed as ).

Note: This implies that, in general, combining these keywords with other component values in the same declaration results in an invalid declaration. For example, background: url(corner.png) no-repeat, inherit; is invalid.

2.2. Component value combinators

Component values can be arranged into property values as follows:

  • Juxtaposing components means that all of them must occur, in the given order.
  • A double ampersand () separates two or more components, all of which must occur, in any order.
  • A double bar () separates two or more options: one or more of them must occur, in any order.
  • A bar () separates two or more alternatives: exactly one of them must occur.
  • Brackets ([ ]) are for grouping.

Juxtaposition is stronger than the double ampersand, the double ampersand is stronger than the double bar, and the double bar is stronger than the bar. Thus, the following lines are equivalent:

a b | c || d && e f [ a b ] | [ c || [ d && [ e f ]]]

For reorderable combinators (||, &&), ordering of the grammar does not matter: components in the same grouping may be interleaved in any order. Thus, the following lines are equivalent:

a || b || c b || a || c

2.3. Component value multipliers

Every type, keyword, or bracketed group may be followed by one of the following modifiers:

  • An asterisk () indicates that the preceding type, word, or group occurs zero or more times.
  • A plus () indicates that the preceding type, word, or group occurs one or more times.
  • A question mark () indicates that the preceding type, word, or group is optional (occurs zero or one times).
  • A single number in curly braces () indicates that the preceding type, word, or group occurs times.
  • A comma-separated pair of numbers in curly braces () indicates that the preceding type, word, or group occurs at least and at most times. The may be omitted ({,}) to indicate that there must be at least repetitions, with no upper bound on the number of repetitions.
  • A hash mark () indicates that the preceding type, word, or group occurs one or more times, separated by comma tokens (which may optionally be surrounded by white space and/or comments). It may optionally be followed by the curly brace forms, above, to indicate precisely how many times the repetition occurs, like <length>#{1,4}.
  • An exclamation point () after a group indicates that the group is required and must produce at least one value; even if the grammar of the items within the group would otherwise allow the entire contents to be omitted, at least one component value must not be omitted.

For repeated component values (indicated by *, +, or #), UAs must support at least 20 repetitions of the component. If a property value contains more than the supported number of repetitions, the declaration must be ignored as if it were invalid.

2.4. Combinator and Multiplier Patterns

There are a small set of common ways to combine multiple independent component values in particular numbers and orders. In particular, it’s common to want to express that, from a set of component value, the author must select zero or more, one or more, or all of them, and in either the order specified in the grammar or in any order.

All of these can be easily expressed using simple patterns of combinators and multipliers:

in order any order
zero or more A? B? C? A? || B? || C?
one or more [ A? B? C? ]!A || B || C
all A B C A && B && C

Note that all of the "any order" possibilities are expressed using combinators, while the "in order" possibilities are all variants on juxtaposition.

2.5. Component values and white space

Unless otherwise specified, white space and/or comments may appear before, after, and/or between components combined using the above combinators and multipliers.

Note: In many cases, spaces will in fact be required between components in order to distinguish them from each other. For example, the value 1em2em would be parsed as a single <dimension-token> with the number 1 and the identifier em2em, which is an invalid unit. In this case, a space would be required before the 2 to get this parsed as the two lengths 1em and 2em.

2.6. Property value examples

Below are some examples of properties with their corresponding value definition fields

Property Value definition field Example value
orphans<integer> 3
text-alignleft | right | center | justify center
padding-top<length> | <percentage> 5%
outline-color<color> | invert #fefefe
text-decorationnone | underline || overline || line-through || blink overline underline
font-family[ <family-name> | <generic-family> ]# "Gill Sans", Futura, sans-serif
border-width[ <length> | thick | medium | thin ]{1,4} 2px medium 4px
text-shadow[ inset? && [ <length>{2,4} && <color>? ] ]# | none 3px 3px rgba(50%, 50%, 50%, 50%), lemonchiffon 0 0 4px inset

3. Textual Data Types

, generically denoted by , consist of a sequence of characters conforming to the <ident-token> grammar. [CSS3SYN] Identifiers cannot be quoted; otherwise they would be interpreted as strings.

3.1. Pre-defined Keywords

In the value definition fields, keywords with a pre-defined meaning appear literally. Keywords are CSS identifiers and are interpreted ASCII case-insensitively (i.e., [a-z] and [A-Z] are equivalent).

For example, here is the value definition for the border-collapse property: Value: collapse | separate

And here is an example of its use:

table { border-collapse: separate }

3.1.1. CSS-wide keywords: initial, inherit and unset

As defined above, all properties accept the , which represent value computations common to all CSS properties.

The initial keyword represents the value specified as the property’s initial value. The inherit keyword represents the computed value of the property on the element’s parent. The unset keyword acts as either inherit or initial, depending on whether the property is inherited or not. All of these keywords are normatively defined in the Cascade module. [CSS3CASCADE]

Other CSS specifications can define additional CSS-wide keywords.

3.2. Author-defined Identifiers: the <custom-ident> type

Some properties accept arbitrary author-defined identifiers as a component value. This generic data type is denoted by , and represents any valid CSS identifier that would not be misinterpreted as a pre-defined keyword in that property’s value definition. Such identifiers are fully case-sensitive, even in the ASCII range (e.g. example and EXAMPLE are two different, unrelated user-defined identifiers).

The CSS-wide keywords are not valid <custom-ident>s. The default keyword is reserved and is also not a valid <custom-ident>. Specifications using <custom-ident> must specify clearly what other keywords are excluded from <custom-ident>, if any—for example by saying that any pre-defined keywords in that property’s value definition are excluded. Excluded keywords are excluded in all ASCII case permutations.

When parsing positionally-ambiguous keywords in a property value, a <custom-ident> production can only claim the keyword if no other unfulfilled production can claim it.

For example, the shorthand declaration animation: ease-in ease-out is equivalent to the longhand declarations animation-timing-function: ease-in; animation-name: ease-out;. ease-in is claimed by the <single-timing-function> production belonging to animation-timing-function, leaving ease-out to be claimed by the <custom-ident> production belonging to animation-name.

Note: When designing grammars with <custom-ident>, the <custom-ident> should always be "positionally unambiguous", so that it’s impossible to conflict with any keyword values in the property.

3.3. Quoted Strings: the <string> type

are denoted by and consist of a sequence of characters delimited by double quotes or single quotes. They correspond to the <string-token> production in the CSS Syntax Module[CSS3SYN].

Double quotes cannot occur inside double quotes, unless escaped (as or as ). Analogously for single quotes ( or ). content: "this is a 'string'."; content: "this is a \"string\"."; content: 'this is a "string".'; content: 'this is a \'string\'.'

It is possible to break strings over several lines, for aesthetic or other reasons, but in such a case the newline itself has to be escaped with a backslash (\). The newline is subsequently removed from the string. For instance, the following two selectors are exactly the same:

Example(s):

a[title="a not s\ o very long title"] {/*...*/} a[title="a not so very long title"] {/*...*/}

Since a string cannot directly represent a newline, to include a newline in a string, use the escape "\A". (Hexadecimal A is the line feed character in Unicode (U+000A), but represents the generic notion of "newline" in CSS.)

3.4. Resource Locators: the <url> type

A is a pointer to a resource and is a functional notation denoted by <url>. The syntax of a <url> is:

= url( <string><url-modifier>* )
Below is an example of a URL being used as a background image: body { background: url("http://www.example.com/pinkish.gif") }

In addition to the syntax defined above, a <url> can sometimes be written in other ways:

  • A <url> can be written without quotation marks around the URL itself. (This syntax is specially-parsed as a <url-token>. [CSS3SYN])

    For example, the following declarations are identical: background: url("http://www.example.com/pinkish.gif"); background: url(http://www.example.com/pinkish.gif);
  • Some CSS contexts (such as @import) allow a <url> to be represented by a bare <string>, without the url() wrapper. In such cases the string behaves identically to a url() function containing that string.

    For example, the following statements are identical: @import url("base-theme.css"); @import "base-theme.css";

Note: The special parsing rules for the legacy quotation-mark–less <url> syntax means that parentheses, whitespace characters, single quotes (') and double quotes (") appearing in a URL must be escaped with a backslash, e.g. url(open\(parens), url(close\)parens). Depending on the type of URL, it might also be possible to write these characters as URL-escapes (e.g. url(open%28parens) or url(close%29parens)) as described in [URL]. Alternately, the URL can be quoted as a string, in which case only newlines and the character used to quote the string need to be escaped.

3.4.1. Relative URLs

In order to create modular style sheets that are not dependent on the absolute location of a resource, authors should use relative URLs. Relative URLs (as defined in [URL]) are resolved to full URLs using a base URL. RFC 3986, section 3, defines the normative algorithm for this process. For CSS style sheets, the base URL is that of the style sheet itself, not that of the styled source document. Style sheets embedded within a document have the base URL associated with their container.

When a <url> appears in the computed value of a property, it is resolved to an absolute URL, as described in the preceding paragraph. The computed value of a URL that the UA cannot resolve to an absolute URL is the specified value.

For example, suppose the following rule: body { background: url("tile.png") }

is located in a style sheet designated by the URL:

http://www.example.org/style/basic.css

The background of the source document’s will be tiled with whatever image is described by the resource designated by the URL:

http://www.example.org/style/tile.png

The same image will be used regardless of the URL of the source document containing the .

3.4.2. Empty URLs

If the value of the url() is the empty string (like url("") or url()), the url must resolve to an invalid resource (similar to what the url about:invalid does).

Note: This matches the behavior of empty urls for embedded resources elsewhere in the web platform, and avoids excess traffic re-requesting the stylesheet or host document due to editting mistakes leaving the url() value empty, which are almost certain to be invalid resources for whatever the url() shows up in. Linking on the web platform does allow empty urls, so if/when CSS gains some functionality to control hyperlinks, this restriction can be relaxed in those contexts.

3.4.3. URL Modifiers

The url() function supports specifying additional s, which change the meaning or the interpretation of the URL somehow. A <url-modifier> is either an <ident> or a functional notation.

This specification does not define any <url-modifier>s, but other specs may do so.

Note: A <url> that is either unquoted or not wrapped in url() notation cannot accept any <url-modifier>s.

4. Numeric Data Types

Properties may restrict numeric values to some range. If the value is outside the allowed range, the declaration is invalid and must be ignored.

CSS theoretically supports infinite precision and infinite ranges for all value types; however in reality implementations have finite capacity. UAs should support reasonably useful ranges and precisions.

4.1. Integers: the <integer> type

Integer values are denoted by .

When written literally, an is one or more decimal digits 0 through 9 and corresponds to a subset of the <number-token> production in the CSS Syntax Module [CSS3SYN]. The first digit of an integer may be immediately preceded by - or + to indicate the integer’s sign.

4.2. Real Numbers: the <number> type

Number values are denoted by , and represent real numbers, possibly with a fractional component.

When written literally, a is either an integer, or zero or more decimal digits followed by a dot (.) followed by one or more decimal digits and optionally an exponent composed of "e" or "E" and an integer. It corresponds to the <number-token> production in the CSS Syntax Module[CSS3SYN]. As with integers, the first character of a number may be immediately preceded by - or + to indicate the number’s sign.

4.3. Percentages: the <percentage> type

Percentage values are denoted by , and indicates a value that is some fraction of another reference value.

When written literally, a consists of a number immediately followed by a percent sign %. It corresponds to the <percentage-token> production in the CSS Syntax Module[CSS3SYN].

Percentage values are always relative to another quantity, for example a length. Each property that allows percentages also defines the quantity to which the percentage refers. This quantity can be a value of another property for the same element, the value of a property for an ancestor element, a measurement of the formatting context (e.g., the width of a containing block), or something else.

In cases where a <percentage> can represent the same quantity as a dimension or number in the same component value position, and can therefore be combined with them in a calc() expression, the following convenience notations may be used in the property grammar:

Equivalent to , where the <percentage> will resolve to a <length>.

Equivalent to , where the <percentage> will resolve to a <frequency>.

Equivalent to , where the <percentage> will resolve to an <angle>.

Equivalent to , where the <percentage> will resolve to a <time>.

Equivalent to , where the <percentage> will resolve to a <number>.

Note: Specifications should never alternate <percentage> in place of a dimension in a grammar unless they are compatible.

4.4. Numbers with Units: dimensions

The general term "dimension" refers to a number with a unit attached to it, and are denoted by .

When written literally, a is a number immediately followed by a unit identifier, which is an identifier. It corresponds to the <dimension-token> production in the CSS Syntax Module[CSS3SYN]. Like keywords, unit identifiers are ASCII case-insensitive.

CSS uses <dimension>s to specify distances (<length>), durations (<time>), frequencies (<frequency>), resolutions (<resolution>), and other quantities.

4.5. Compatible Units

When serializingcomputed values[CSSOM], (those related by a static multiplicative factor, like the 96:1 factor between px and in, or the the computed font-size factor between em and px) are converted into a single . Each group of compatible units defines which among them is the canonical unit that will be used for serialization.

When serializing resolved values that are used values, all value types (percentages, numbers, keywords, etc.) that represent lengths are considered compatible with lengths. Likewise any future API that returns used values must consider any values represent distances/durations/frequencies/etc. as compatible with the relevant class of dimensions, and canonicalize accordingly.

5. Distance Units: the <length> type

Lengths refer to distance measurements and are denoted by in the property definitions. A length is a dimension. However, for zero lengths the unit identifier is optional (i.e. can be syntactically represented as the <number>0).

Properties may restrict the length value to some range. If the value is outside the allowed range, the declaration is invalid and must be ignored.

While some properties allow negative length values, this may complicate the formatting and there may be implementation-specific limits. If a negative length value is allowed but cannot be supported, it must be converted to the nearest value that can be supported.

In cases where the used length cannot be supported, user agents must approximate it in the actual value.

There are two types of length units: relative and absolute.

5.1. Relative lengths

specify a length relative to another length. Style sheets that use relative units can more easily scale from one output environment to another.

The relative units are:

unit relative to
emfont size of the element
exx-height of the element’s font
chwidth of the "0" (ZERO, U+0030) glyph in the element’s font
remfont size of the root element
vw1% of viewport’s width
vh1% of viewport’s height
vmin1% of viewport’s smaller dimension
vmax1% of viewport’s larger dimension

Child elements do not inherit the relative values as specified for their parent; they inherit the computed values.

5.1.1. Font-relative lengths: the em, ex, ch, rem units

Aside from rem (which refers to the font-size of the root element), the refer to the font metrics of the element on which they are used. The exception is when they occur in the value of the font-size property itself, in which case they refer to the computed font metrics of the parent element (or the computed font metrics corresponding to the initial values of the font property, if the element has no parent).

Equal to the computed value of the font-size property of the element on which it is used.
The rule: h1 { line-height: 1.2em }

means that the line height of elements will be 20% greater than the font size of element. On the other hand:

h1 { font-size: 1.2em }

means that the font size of elements will be 20% greater than the computed font size inherited by elements.

Equal to the used x-height of the first available font[CSS3-FONTS]. The x-height is so called because it is often equal to the height of the lowercase "x". However, an ex is defined even for fonts that do not contain an "x". The x-height of a font can be found in different ways. Some fonts contain reliable metrics for the x-height. If reliable font metrics are not available, UAs may determine the x-height from the height of a lowercase glyph. One possible heuristic is to look at how far the glyph for the lowercase "o" extends below the baseline, and subtract that value from the top of its bounding box. In the cases where it is impossible or impractical to determine the x-height, a value of 0.5em must be assumed.
Equal to the used advance measure of the "0" (ZERO, U+0030) glyph found in the font used to render it. (The of a glyph is its advance width or height, whichever is in the inline axis of the element.)

Note: The advance measure of a glyph depends on writing-mode and text-orientation as well as font settings, text-transform, and any other properties that affect glyph selection or orientation.

In the cases where it is impossible or impractical to determine the measure of the “0” glyph, it must be assumed to be 0.5em wide by 1em tall. Thus, the ch unit falls back to 0.5em in the general case, and to 1em when it would be typeset upright (i.e. writing-mode is vertical-rl or vertical-lr and text-orientation is upright).

Equal to the computed value of font-size on the root element. When specified on the font-size property of the root element, the rem units refer to the property’s initial value.

5.1.2. Viewport-percentage lengths: the vw, vh, vmin, vmax units

The are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly. However, when the value of overflow on the root element is auto, any scroll bars are assumed not to exist. Note that the initial containing block’s size is affected by the presence of scrollbars on the viewport.

For paged media, the exact definition of the viewport-percentage lengths is deferred to [CSS3PAGE].

Equal to 1% of the width of the initial containing block.
In the example below, if the width of the viewport is 200mm, the font size of elements will be 16mm (i.e. (8×200mm)/100). h1 { font-size: 8vw }
Equal to 1% of the height of the initial containing block.
Equal to the smaller of vw or vh.
Equal to the larger of vw or vh.

5.2. Absolute lengths: the cm, mm, q, in, pt, pc, px units

The are fixed in relation to each other and anchored to some physical measurement. They are mainly useful when the output environment is known. The absolute units consist of the (in, cm, mm, pt, pc, q) and the (px):

unit name equivalence
centimeters 1cm = 96px/2.54
millimeters 1mm = 1/10th of 1cm
quarter-millimeters 1q = 1/40th of 1cm
inches 1in = 2.54cm = 96px
picas 1pc = 1/6th of 1in
points 1pt = 1/72th of 1in
pixels 1px = 1/96th of 1in
h1 { margin: 0.5in } /* inches */ h2 { line-height: 3cm } /* centimeters */ h3 { word-spacing: 4mm } /* millimeters */ h3 { letter-spacing: 1Q } /* quarter-millimeters */ h4 { font-size: 12pt } /* points */ h4 { font-size: 1pc } /* picas */ p { font-size: 12px } /* px */

All of the absolute length units are compatible, and px is their canonical unit.

For a CSS device, these dimensions are anchored either

  1. by relating the physical units to their physical measurements, or
  2. by relating the pixel unit to the reference pixel.

For print media and similar high-resolution devices, the anchor unit should be one of the standard physical units (inches, centimeters, etc). For lower-resolution devices, and devices with unusual viewing distances, it is recommended instead that the anchor unit be the pixel unit. For such devices it is recommended that the pixel unit refer to the whole number of device pixels that best approximates the reference pixel.

Note: If the anchor unit is the pixel unit, the physical units might not match their physical measurements. Alternatively if the anchor unit is a physical unit, the pixel unit might not map to a whole number of device pixels.

Note: This definition of the pixel unit and the physical units differs from previous versions of CSS. In particular, in previous versions of CSS the pixel unit and the physical units were not related by a fixed ratio: the physical units were always tied to their physical measurements while the pixel unit would vary to most closely match the reference pixel. (This change was made because too much existing content relies on the assumption of 96dpi, and breaking that assumption broke the content.)

The is the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm’s length. For a nominal arm’s length of 28 inches, the visual angle is therefore about 0.0213 degrees. For reading at arm’s length, 1px thus corresponds to about 0.26 mm (1/96 inch).

The image below illustrates the effect of viewing distance on the size of a reference pixel: a reading distance of 71 cm (28 inches) results in a reference pixel of 0.26 mm, while a reading distance of 3.5 m (12 feet) results in a reference pixel of 1.3 mm.

This second image illustrates the effect of a device’s resolution on the pixel unit: an area of 1px by 1px is covered by a single dot in a low-resolution device (e.g. a typical computer display), while the same area is covered by 16 dots in a higher resolution device (such as a printer).

6. Other Quantities

6.1. Angle Units: the <angle> type and deg, grad, rad, turn units

Angle values are <dimension>s denoted by . However, for zero angles the unit identifier is optional (i.e. can be syntactically represented as the number0). The angle unit identifiers are:

Degrees. There are 360 degrees in a full circle.
Gradians, also known as "gons" or "grades". There are 400 gradians in a full circle.
Radians. There are 2π radians in a full circle.
Turns. There is 1 turn in a full circle.

For example, a right angle is 90deg or 100grad or 0.25turn or approximately 1.57rad.

All <angle> units are compatible, and deg is their canonical unit.

By convention, when an angle denotes a direction in CSS, it is typically interpreted as a , where 0deg is "up" or "north" on the screen, and larger angles are more clockwise (so 90deg is "right" or "east").

For example, in the linear-gradient() function, the <angle> that determines the direction of the gradient is interpreted as a bearing angle.

6.2. Duration Units: the <time> type and s

Arrays are ordered, integer-indexed collections of any object.

Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array—that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

Creating Arrays

A new array can be created by using the literal constructor . Arrays can contain different types of objects. For example, the array below contains an Integer, a String and a Float:

An array can also be created by explicitly calling Array.new with zero, one (the initial size of the Array) or two arguments (the initial size and a default object).

Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.

To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays:

This is also a quick way to build up multi-dimensional arrays:

An array can also be created by using the Array() method, provided by Kernel, which tries to call #to_ary, then #to_a on its argument.

Array(=> “a”, :b => “b”) #=> [[:a, “a”], [:b, “b”]]

Example Usage

In addition to the methods it mixes in through the Enumerable module, the Array class has proprietary methods for accessing, searching and otherwise manipulating arrays.

Some of the more common ones are illustrated below.

Accessing Elements

Elements in an array can be retrieved using the Array#[] method. It can take a single integer argument (a numeric index), a pair of arguments (start and length) or a range. Negative indices start counting from the end, with -1 being the last element.

Another way to access a particular array element is by using the #at method

The #slice method works in an identical manner to Array#[].

To raise an error for indices outside of the array bounds or else to provide a default value when that happens, you can use #fetch.

The special methods #first and #last will return the first and last elements of an array, respectively.

To return the first elements of an array, use #take

#drop does the opposite of #take, by returning the elements after elements have been dropped:

Obtaining Information about an Array

Arrays keep track of their own length at all times. To query an array about the number of elements it contains, use #length, #count or #size.

To check whether an array contains any elements at all

To check whether a particular item is included in the array

Adding Items to Arrays

Items can be added to the end of an array by using either #push or #<<

#unshift will add a new item to the beginning of an array.

With #insert you can add a new element to an array at any position.

Using the #insert method, you can also insert multiple values at once:

Removing Items from an Array

The method #pop removes the last element in an array and returns it:

To retrieve and at the same time remove the first item, use #shift:

To delete an element at a particular index:

To delete a particular element anywhere in an array, use #delete:

A useful method if you need to remove values from an array is #compact:

Another common need is to remove duplicate elements from an array.

It has the non-destructive #uniq, and destructive method #uniq!

Iterating over Arrays

Like all classes that include the Enumerable module, Array has an each method, which defines what elements should be iterated over and how. In case of Array's #each, all elements in the Array instance are yielded to the supplied block in sequence.

Note that this operation leaves the array unchanged.

Another sometimes useful iterator is #reverse_each which will iterate over the elements in the array in reverse order.

The #map method can be used to create a new array based on the original array, but with the values modified by the supplied block:

Selecting Items from an Array

Elements can be selected from an array according to criteria defined in a block. The selection can happen in a destructive or a non-destructive manner. While the destructive operations will modify the array they were called on, the non-destructive methods usually return a new array with the selected elements, but leave the original array unchanged.

Non-destructive Selection

Destructive Selection

#select! and #reject! are the corresponding destructive methods to #select and #reject

Similar to #select vs. #reject, #delete_if and #keep_if have the exact opposite result when supplied with the same block:

0 thoughts on “Block Supersedes Default Value Argument Essay

Leave a Reply

Your email address will not be published. Required fields are marked *