Collect values and repeat work
Use arrays, hashes, and each to process collections.
- Iterate through a collection and calculate a result.
An array stores an ordered sequence. A hash maps keys to values. Use each to run a block for every element; block parameters go between vertical bars. Ruby also has while and times for repetition, but collection methods often make intent especially clear.
1scores = [8, 7, 10]
2total = 0
3scores.each do |score|
4 total += score
5end
6puts total
7profile = { name: "Ada", active: true }
8puts profile[:name]25 Ada
Array indexes start at zero. A hash literal uses key-value pairs, and symbol keys can use the concise name: value syntax. Use square brackets to read a value by its key.
Key takeaways
Iterate through a collection and calculate a result.
Ruby methods and blocks help express operations clearly.
Read each result and error message as feedback about your code.
Lesson quiz
4 questions · pass with 3 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Ruby
Write Ruby in the editor and run it against sample input. Your code is sent to Wandbox to run.
Sum a list of numbers
Read a count followed by that many integers. Store them in an array and print their sum using each.
- Three values
- Includes a negative
Ruby runs through Wandbox, a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…