liveBook · Manning

Size method

As explained in The Well-Grounded Rubyist, Fourth Edition

The size method returns the number of elements in a Ruby collection.

Ruby’s size method reports how many elements or characters a collection-like object contains. For the string "Ruby is a cool language.", string.size returns 24; length is a synonym. section 8.1.3

The meaning of size follows the receiver:

  • A String returns its number of characters. section 8.1.3
  • An Array returns the number of elements, which can determine how many times an indexed iteration must yield. section 6.3.6
  • A Hash returns the number of key/value pairs; length is a synonym. section 9.3.6

Using size to implement iteration

An indexed iterator can keep a counter, stop when the counter equals size, yield self[c] on each pass, and return the original array. This makes size a practical boundary for traversing every array element. section 6.3.6

>> string = "Ruby is a cool language."
>> string.size
=> 24

Inspect a concrete String#size call and its returned character count. section 8.1.3

Table 9.3 Common hash query methods and their meanings

Method name/Sample call

Meaning

h.has_key?(1)

True if h has the key 1

h.include?(1)

Synonym for has_key?

h.key?(1)

Synonym for has_key?

h.member?(1)

Synonym for has_key?

h.has_value?("three")

True if any value in h is "three"

h.value?("three")

Synonym for has_value?

h.empty?

True if h has no key/value pairs

h.size

Number of key/value pairs in h

Compare Hash#size with related state-query methods and see that it counts pairs rather than keys or values separately. section 9.3.6

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines receiver-specific counts and demonstrates size inside a custom indexed iterator without detailing implementation internals.
Examples
Uses a 24-character string, a five-element array, a hash query table, and a custom my_each implementation.
What it assumes
Assumes basic Ruby objects, method calls, arrays, hashes, strings, indexing, and block-based iteration.
What you can do after
Apply it via Ruby methods to count collection contents or establish an array iteration boundary.
How it connects
Connects size with length, strings, arrays, hashes, iteration, blocks, and indexed access.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.