Practice

Ruby exercises

Make a change, predict what it will do, and compare the result.

  1. 1

    Ruby Basics

    Store text and print it.

    Adapt the lesson example. Change one value or element, predict the result, and explain why it changes.

    Show starting example
    Ruby
    name = "Ada"
    puts "Hello, #{name}"
  2. 2

    Ruby Arrays

    Visit each value in an array.

    Adapt the lesson example. Change one value or element, predict the result, and explain why it changes.

    Show starting example
    Ruby
    scores = [82, 91, 76]
    scores.each do |score|
      puts score
    end
  3. 3

    Ruby Methods and map

    Define a method and transform an array with map.

    Predict [1, 2, 3].map { |n| n + 10 }.

    Reveal answer and reasoning

    It returns [11, 12, 13].

    Show starting example
    Ruby
    def average(values)
      values.sum / values.size.to_f
    end
    
    puts average([82, 91, 76, 95])
    puts [1, 2, 3].map { |n| n * n }.inspect
  4. 4

    Ruby Classes

    Keep state in an instance variable and read it with attr_reader.

    Make Counter writable too.

    Reveal answer and reasoning

    Replace attr_reader with attr_accessor :value so counter.value = 5 works.

    Show starting example
    Ruby
    class Counter
      attr_reader :value
    
      def initialize
        @value = 0
      end
    
      def increment
        @value += 1
      end
    end
    
    counter = Counter.new
    counter.increment
    counter.increment
    puts counter.value
  5. 5

    Ruby Hashes

    Store key-value pairs and iterate over them.

    What does scores["Zed"] return?

    Reveal answer and reasoning

    nil, because that key is absent.

    Show starting example
    Ruby
    scores = { "Ada" => 91, "Grace" => 88 }
    scores["Linus"] = 79
    scores.each do |name, score|
      puts "#{name}: #{score}"
    end
    puts scores.size