Lesson 4 of 8 · 9 min

Arrays and blocks

Arrays hold ordered lists:

fruits = ["mango", "banana", "guava"]
fruits << "orange"           # add to the end
fruits.first                 # "mango"
fruits.last                  # "orange"
fruits.length                # 4
fruits.include?("banana")    # true
fruits.sort                  # A to Z (a new array)
%w[a b c]                    # shortcut for ["a", "b", "c"]

Methods ending in ? return true or false. Methods ending in ! (like sort!) change the array itself instead of returning a new one.

Blocks do the real work

numbers = [1, 2, 3, 4, 5]

numbers.map { |n| n * 10 }          # [10, 20, 30, 40, 50]  change each item
numbers.select { |n| n.even? }      # [2, 4]                keep some
numbers.reject { |n| n.even? }      # [1, 3, 5]             drop some
numbers.sum                         # 15
numbers.max_by { |n| -n }           # 1                     the item with the largest result
%w[kiwi fig banana].sort_by { |w| w.length }   # ["fig", "kiwi", "banana"]

When the block only calls one method on each item, there is a shortcut: names.map(&:upcase) is the same as names.map { |n| n.upcase }.

Dividing two whole numbers gives a whole number in Ruby (7 / 2 is 3). Use .to_f for a decimal result: 7.to_f / 2 is 3.5.

Your task

  1. passed(scores): scores of 50 or more.
  2. curve(scores): every score plus 5, but never above 100.
  3. longest_name(names): the longest name.
  4. average(scores): the mean as a float, rounded to 1 decimal place.
main.rb
def passed(scores)
end

def curve(scores)
end

def longest_name(names)
end

def average(scores)
end

p curve([40, 97, 100])

Ruby 3.4 runs right here in your browser. The first run downloads about 16 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…