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
| 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:
&:roundis shorthand for{ |x| x.round }.itrefers to the block's single argument (Ruby 3.4+):sort_by { -it }is the same assort_by { |x| -x }.- Chain methods to build pipelines: filter → transform → combine.
Hashes
A hash maps keys to values. Symbol keys are the most common:
fetch is stricter than []: with no default, a missing key raises an error instead of quietly returning nil, which catches typos early.
Transforming hashes
Counting and grouping
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:
<<~JSON … JSON is a heredoc: a multi-line string. The ~ removes the indentation.
Sets
A Set holds unique values with fast membership checks:
Ranges
Practice
- Given
[3, 7, 3, 9, 1, 7], print the unique values sorted from largest to smallest. - From an array of words, build a hash of word → length, then print the longest word.
- Group
[1, 2, 3, 4, 5, 6, 7, 8, 9]intooddandevenwithgroup_by. - Parse this JSON and print each product's name and total:
[{"name":"Pen","qty":3,"price":1.5},{"name":"Pad","qty":2,"price":4}].
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?