Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

RB
Ruby
0/12 completed
Beginner
Hello RubyVariables and typesConditions and loopsMethods
Intermediate
Arrays and hashesBlocks, procs and iteratorsClasses and objectsModules and mixins
Advanced
Exceptions and filesMetaprogramming
Pro
Gems, Bundler and testingRuby on Rails basics
Tracks / Ruby / Intermediate

Arrays and hashes

Two collections cover almost everything in Ruby: the Array (an ordered list) and the Hash (key → value pairs). Both come with a huge set of methods, so tasks that need a loop in other languages are often one line in Ruby.

Arrays

Ruby · editable
Method Does
a << x, push Add to the end
pop, shift Remove from the end / front
a[i], a[-1], a[1..3] Read by position or range
first(n), last(n) First / last n elements
include?, index Search
sort, reverse, uniq, flatten, compact New, rearranged arrays (! versions change the array)
join(", ") Combine into a string

Transforming arrays

This is where Ruby shines. Each of these takes a block and returns a new array or value:

Ruby · editable
  • &:round is shorthand for { |x| x.round }.
  • it refers to the block's single argument (Ruby 3.4+): sort_by { -it } is the same as sort_by { |x| -x }.
  • Chain methods to build pipelines: filter → transform → combine.

Hashes

A hash maps keys to values. Symbol keys are the most common:

Ruby · editable

fetch is stricter than []: with no default, a missing key raises an error instead of quietly returning nil, which catches typos early.

Transforming hashes

Ruby · editable

Counting and grouping

Ruby · editable

Hash.new(0) gives every missing key a default of 0, which makes counting easy (text.split.tally does the same in one call).

Nested data

Real data (like parsed JSON) is hashes inside arrays inside hashes. dig reads deep values safely:

Ruby · editable

<<~JSON … JSON is a heredoc: a multi-line string. The ~ removes the indentation.

Sets

A Set holds unique values with fast membership checks:

Ruby · editable

Ranges

Ruby · editable

Practice

  1. Given [3, 7, 3, 9, 1, 7], print the unique values sorted from largest to smallest.
  2. From an array of words, build a hash of word → length, then print the longest word.
  3. Group [1, 2, 3, 4, 5, 6, 7, 8, 9] into odd and even with group_by.
  4. Parse this JSON and print each product's name and total: [{"name":"Pen","qty":3,"price":1.5},{"name":"Pad","qty":2,"price":4}].
✎ Check your understanding

1.What does [1, 2, 3].map { |x| x * 2 } return?

2.What does user[:email] return if the key doesn't exist?

3.What is Hash.new(0) useful for?

4.Which method reads data[:a][:b][:c] without crashing when a level is missing?

← Methods