Arrays in Ruby

Arrays are data structures that allow storing an ordered collection of elements of any type. They are a fundamental tool in Ruby for working with data sets.

Creation and access to elements: Link to heading

  • They can be created using square brackets and separating elements with commas.
  • The size of the array can be obtained with the size method.
  • Elements can be accessed by their index, starting with 0.
  • Negative indices can be used to access elements from the end of the array.

Examples: Link to heading

letters = ["q", "w", "e", "r", "t"]

letters.class # => Array

letters.size # => 5

letters[2] # => "e"

letters[-1] # => "t"

letters[100] # => nil

letters[-100] # => nil

lyrics.include? "q" # => true

lyrics.include? "b" # => false

Useful methods: Link to heading

  • first: Gets the first element of the array.
  • last: Gets the last element of the array.
  • count: Counts the number of elements that meet a condition.
  • map: Transforms each element of the array and returns a new array.
  • select: Filters the elements of the array and returns a new array with those that meet a condition.
  • min: Gets the minimum element of the array.
  • max: Gets the maximum element of the array.
  • sum: Sum all the elements of the array.

Examples: Link to heading

letters = ["q", "w", "e", "r", "t"]

letters.first # => "q"

letters.last # => "t"

letters.count { |x| x == "q" } # => 1

[1, 2, 3, 4, 5].count { |x| x.even? } # => 2

[1, 2, 3, 4, 5].map { |x| x \* 2 } # => [2, 4, 6, 8, 10]

[1, 2, 3, 4, 5].select { |x| xodd? } # => [1, 3, 5]

[1, 2, 3, 4, 5].min # => 1

[1, 2, 3, 4, 5].max # => 5

[1, 2, 3, 4, 5].sum # => 15

Handling different types of data: Link to heading

Arrays can store elements of any type, including other arrays.

Example: Link to heading

array = [4, 4.5, "string", :symbol, []]

array.map { |x| x.class } # => [Integer, Float, String, Symbol, Array]

Work with strings: Link to heading

Strings can be split into arrays using the split method.

Example: Link to heading

"hello world".split(" ") # => ["hello", "world"]

"hello world".split(" ").size # => 2

"hello world".split(" ").map { |x| x.upcase } # => ["HELLO", "WORLD"]

"hello world".split(" ").map { |x| x.upcase }.join("\n") # => "HELLO\nWORLD"

puts("hello world".split(" ").map { |x| x.upcase }.join("\n")) # HELLO WORLD

Sort arrays: Link to heading

They can be sorted using the sort method.

Example: Link to heading

letters = ["q", "w", "e", "r", "t"]

letters.sort # => ["e", "q", "r", "t", "w"]

sort_letters = letters.sort

letters # => ["q", "w", "e", "r", "t"]

sort_letters = letters.sort!

letters # => ["e", "q", "r", "t", "w"] # The original array is modified

Arrays are a powerful tool for working with data in Ruby. Their flexibility and simplicity make them a fundamental part of the language.

<< Object and symbol identifiers in Ruby Hashes in Ruby >>