Practice Ruby arrays, selection blocks and reusable methods.

Before starting: Basic variables and arrays.

Practice project: Extend the examples into a small Ruby study demo. Explain the setup, one normal case and one failure or boundary case.

Start here: concepts and guided practice

  1. Read and transform a Ruby array

    Ruby uses objects and methods to express tasks. Here an array stores scores, sum calculates a total and puts displays it. Changing the values changes the result; an empty array sum is zero.

    Ruby interpreter; save as scores.rb and run ruby scores.rb

    scores = [4, 7, 2]
    total = scores.sum
    puts "Total: #{total}"
    Check the output
    Total: 13

    Try an empty array and predict zero.

  2. Ruby: keep only matching values

    select builds an array containing values that satisfy a block. The original array stays available. Compare the boundary explicitly instead of assuming positive means at least zero.

    Ruby interpreter; save as study.rb and run ruby study.rb.

    scores = [0, 4, -2, 7]
    kept = scores.select { |score| score > 0 }
    puts kept.join(", ")
    Check the output
    4, 7

    Change > to >=; explain why 0 is now included.

  3. Ruby: return a result from a method

    A method names a reusable calculation. In this short method the final expression is its return value. puts displays the returned value separately.

    Ruby interpreter; save as study.rb and run ruby study.rb.

    def minutes_for(lessons)
      lessons * 15
    end
    puts minutes_for(3)
    Check the output
    45

    Decide how your program should handle a negative lesson count.

Open the Ruby learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.