Explain it simply
Explain it simply
This lesson teaches no new syntax. It is a workout for what the Basic chapters covered: variables, methods, conditionals, arrays, hashes and strings. The six tasks are small on purpose, and each hides one or two edge cases that real input will eventually hit.
Work like this: read a task, write your own solution in a file, predict what it prints, run it with ruby, and only then open the reference solution. Type the code instead of pasting it. A mistake you find yourself is one you will remember.
Problem → Why → Solution
The problem: a first draft that only works for the sample
The first draft of an exercise usually works for the example in the task and for nothing else. Take even_or_odd. A draft written from habit in another language might use n / 2 == 0, or n % 2 == 1. In Ruby, 7 / 2 is 3, not 3.5, because dividing two Integers rounds down, so n / 2 == 0 is true only for 0 and 1. The remainder test looks safer, but the same expression behaves differently in JavaScript or C for negative numbers, so a habit alone is not something to trust.
Other inputs break drafts too: an empty array, a nil in the middle of an array, a name that appears twice, two students tied for first place, a Myanmar word whose length is not its number of bytes. None of these appear in the task's example, which is why they have to be thought about on purpose.
def even_or_odd(n)
n / 2 == 0 ? "Even" : "Odd" # wrong: 7 / 2 is 3, an Integer
end
puts even_or_odd(7) # Odd (right, by luck)
puts even_or_odd(10) # Odd (wrong: 10 / 2 is 5, not 0)
puts even_or_odd(1) # Even (wrong: 1 / 2 is 0)
puts [1, nil, 3].sum # TypeError: nil can't be coerced into IntegerWhy does nothing warn you?
The draft passes the one example, so nothing warns you. Edge cases are the inputs the author did not think of, and they are also the inputs users send. The remedy is a habit rather than a feature: before writing the body, list the strange inputs, decide what each should do, and write them as extra calls next to the obvious one.
Core concept: from the task description to a checked solution
A good exercise solution is built in the same order every time. That order keeps the work small and makes the edge cases hard to forget.
1. Write the method signature and its promise
Name the method, its parameters and what it returns, and write the promise as a comment: sum_numbers takes an Array and returns a number, and an empty array gives 0. If you cannot state the promise in one sentence, you have not understood the task yet.
2. List the strange inputs
Ask for the smallest, emptiest and oddest input: [], nil, a single element, duplicates, negative numbers, a tie, text with leading spaces, Myanmar text. For each one decide whether to return a sensible value, skip it, or raise ArgumentError. Write these decisions down before the body.
3. Pick the Ruby tool that matches the shape of the data
Let the shape of the data choose the iteration: sum for totals, select and map for filtering and transforming, tally or group_by for counting, max_by and min_by for "the best one". A hand-written each loop with an accumulator is still correct, only longer.
4. Return values, print in the caller
A method that returns a value can be called by other code and compared in a test; a method that prints can only be checked by eye. Do the work in the method and let the demo code at the bottom of the file print.
5. Predict, run, compare
Write the output you expect, run the file, and investigate every difference. A surprise tells you something about Ruby or about your assumption, and both are worth knowing.
| Data you have | Ruby tool | Edge case to check |
|---|---|---|
| Array of numbers | sum, each + accumulator | [] gives 0, nil elements, floats |
| Words in a sentence | split, reverse, join | Extra spaces, empty string, nil |
| (name, score) pairs | Hash with fetch, group_by | Duplicate names, empty list |
| Hash of scores | values.max, select, keys.sort | Ties, empty Hash |
| Text | length, bytesize, split | Myanmar and emoji |
- Write the signature and the promise
- List the strange inputs as extra calls
- Pick the tool that fits the data
- Predict the output, then run
- Explain every difference
If a step fails, go back one step, not to the start: a wrong answer usually means a missing edge case, not a wrong signature.
General pattern
def name(input)
raise ArgumentError, "expected an Array" unless input.is_a?(Array)
return default if input.empty?
result = input.compact.map { |item| transform(item) }
result.select { |item| condition?(item) }
end
puts name([])
puts name([1, nil, 3])The first lines check the expected input type and return early for an empty one. The rest is the normal work, and the calls at the bottom try two strange inputs side by side.
Reference solutions for the six tasks
Compare these solutions with your own only after you have tried. They go further than the examples in the tasks: even_or_odd is called with 0, a negative number, a float and nil, and sum_numbers with an empty array and nil elements. The show helper prints each call next to its result, so an edge case sits beside the normal one. Results that contain a Hash use Ruby 4.0.9's print format ({"Aye" => 90}); older versions print {"Aye"=>90}.
# Task 1: only Integers have a meaningful "even or odd".
def even_or_odd(n)
raise ArgumentError, "expected an Integer, got #{n.inspect}" unless n.is_a?(Integer)
(n % 2).zero? ? "Even" : "Odd"
end
# Task 2: an empty array sums to 0, nil entries are skipped.
def sum_numbers(numbers)
unless numbers.is_a?(Array)
raise ArgumentError, "expected an Array, got #{numbers.inspect}"
end
numbers.compact.sum
end
# Task 3: split with no argument ignores extra spaces, so the result is tidy.
def reverse_words(sentence)
sentence.to_s.split.reverse.join(" ")
end
# Task 4: the highest score per student, even when a name appears twice.
def best_scores(pairs)
best = {}
pairs.each do |name, score|
best[name] = [best.fetch(name, score), score].max
end
best
end
# Task 5: every student tied for the top score, sorted by name.
def top_students(scores)
return [] if scores.empty?
highest = scores.values.max
scores.select { |_name, score| score == highest }.keys.sort
end
# Task 6: length counts characters (code points), bytesize counts UTF-8 bytes.
def text_stats(text)
"characters=#{text.length} bytes=#{text.bytesize} words=#{text.split.size}"
end
# Prints the call and what it returned (or the ArgumentError it raised).
def show(label)
puts "#{label} -> #{yield.inspect}"
rescue ArgumentError => e
puts "#{label} -> ArgumentError: #{e.message}"
end
show("even_or_odd(7)") { even_or_odd(7) }
show("even_or_odd(0)") { even_or_odd(0) }
show("even_or_odd(-3)") { even_or_odd(-3) }
show("even_or_odd(2.5)") { even_or_odd(2.5) }
show("even_or_odd(nil)") { even_or_odd(nil) }
show("sum_numbers([1, 2, 3, 4, 5])") { sum_numbers([1, 2, 3, 4, 5]) }
show("sum_numbers([])") { sum_numbers([]) }
show("sum_numbers([1, nil, 2.5])") { sum_numbers([1, nil, 2.5]) }
show("sum_numbers([0.1, 0.2, 0.3])") { sum_numbers([0.1, 0.2, 0.3]) }
show("sum_numbers(nil)") { sum_numbers(nil) }
show('reverse_words("Ruby is fun")') { reverse_words("Ruby is fun") }
show('reverse_words(" Ruby is fun ")') { reverse_words(" Ruby is fun ") }
show('reverse_words("")') { reverse_words("") }
show("reverse_words(nil)") { reverse_words(nil) }
show("reverse_words(Myanmar)") { reverse_words("မြန်မာစာ ရေးတယ်") }
scores = [["Aye", 70], ["Su", 80], ["Aye", 90], ["Su", 60]]
show("best_scores (duplicate names)") { best_scores(scores) }
show("best_scores([])") { best_scores([]) }
show("top_students (tie)") { top_students({ "Su" => 90, "Aye" => 90, "Kyaw" => 75 }) }
show("top_students({})") { top_students({}) }
puts text_stats("hello world")
puts text_stats("မင်္ဂလာပါ")
puts text_stats("")Code breakdown
- Even or odd
(n % 2).zero? ? "Even" : "Odd"% returns the remainder, and in Ruby the sign of the result follows the divisor, so -3 % 2 is 1 (in C and JavaScript it is -1). That is why -3 is correctly answered "Odd". n.even? gives the same result and reads more clearly. Float and nil have no even?, so anything that is not an Integer raises ArgumentError early.
- Sum with nil and empty input
numbers.compact.sumcompact removes the nils and sum gives 0 for an empty array, whereas reduce(:+) gives nil for an empty array. sum also adds floats more accurately, so [0.1, 0.2, 0.3].sum is 0.6 while reduce(:+) gives 0.6000000000000001.
- Reverse the words
sentence.to_s.split.reverse.join(" ")split with no argument splits on whitespace and ignores extra spaces, so " Ruby is fun " becomes "fun is Ruby". Because of to_s, nil becomes "", and joining an empty array gives "". The same code works on Myanmar words as long as they are separated by spaces.
- Keep the best of duplicates
best[name] = [best.fetch(name, score), score].maxbest.fetch(name, score) gives the stored score when the name was seen before and the current score otherwise, so taking the larger of the two works. pairs.to_h would let the last pair win, losing the highest score when ("Su", 60) comes after ("Su", 80).
- Ties return everyone
scores.select { |_name, score| score == highest }.keys.sortmax_by would return only the first student on a tie, which would be an accident rather than a decision. This solution finds the highest score first, keeps everyone who matches and sorts them, so the result does not depend on the Hash's insertion order. An early return gives [] for an empty Hash.
- Characters versus bytes
"characters=#{text.length} bytes=#{text.bytesize} words=#{text.split.size}"length counts characters (Unicode code points) and bytesize counts UTF-8 bytes. For "hello world" both are 11, but "မင်္ဂလာပါ" has 9 code points and 27 bytes, because each of these Myanmar code points takes three bytes in UTF-8.
- A helper that shows each call
puts "#{label} -> #{yield.inspect}"show runs the block with yield and prints the result with inspect, so strings appear in quotes and nil and "" look different. The rescue at the end of the method catches ArgumentError, so a call that fails still produces a line.
even_or_odd(7) -> "Odd"
even_or_odd(0) -> "Even"
even_or_odd(-3) -> "Odd"
even_or_odd(2.5) -> ArgumentError: expected an Integer, got 2.5
even_or_odd(nil) -> ArgumentError: expected an Integer, got nil
sum_numbers([1, 2, 3, 4, 5]) -> 15
sum_numbers([]) -> 0
sum_numbers([1, nil, 2.5]) -> 3.5
sum_numbers([0.1, 0.2, 0.3]) -> 0.6
sum_numbers(nil) -> ArgumentError: expected an Array, got nil
reverse_words("Ruby is fun") -> "fun is Ruby"
reverse_words(" Ruby is fun ") -> "fun is Ruby"
reverse_words("") -> ""
reverse_words(nil) -> ""
reverse_words(Myanmar) -> "ရေးတယ် မြန်မာစာ"
best_scores (duplicate names) -> {"Aye" => 90, "Su" => 80}
best_scores([]) -> {}
top_students (tie) -> ["Aye", "Su"]
top_students({}) -> []
characters=11 bytes=11 words=2
characters=9 bytes=27 words=1
characters=0 bytes=0 words=0Operators and negative numbers
Two Ruby rules about Integers cause most first-exercise mistakes. First, dividing two Integers rounds down (floors), so -7 / 2 is -4, not -3. Second, the result of % takes the sign of the divisor. The remainder method takes the sign of the dividend and behaves like % in C and JavaScript. The snippet below shows both, plus sum and reduce on an empty array.
puts "7 / 2 = #{7 / 2}"
puts "-7 / 2 = #{-7 / 2}"
puts "7 % 2 = #{7 % 2}"
puts "-7 % 2 = #{-7 % 2}"
puts "-7.remainder(2) = #{-7.remainder(2)}"
puts "[].sum = #{[].sum}"
puts "[].reduce(:+) = #{[].reduce(:+).inspect}"
puts "[0.1, 0.2, 0.3].sum = #{[0.1, 0.2, 0.3].sum}"
puts "[0.1, 0.2, 0.3].reduce(:+) = #{[0.1, 0.2, 0.3].reduce(:+)}"| Expression | Result | Meaning |
|---|---|---|
| 7 / 2 | 3 | Integer division rounds down |
| -7 / 2 | -4 | Rounds toward minus infinity, not toward zero |
| -7 % 2 | 1 | The sign follows the divisor (2) |
| -7.remainder(2) | -1 | The sign follows the dividend (-7) |
Myanmar text: length, bytesize and what the reader sees
A Ruby String is UTF-8, and length counts Unicode code points. In Myanmar text, consonants, vowel signs and medial marks are separate code points, so a word that looks like a handful of letters can have a length of 9 and a bytesize of 27. grapheme_clusters.size counts with Unicode's "what a reader sees as one unit" rules, but even that does not always match a reader's own idea of a letter or syllable. These numbers are results from Ruby 4.0.9.
word = "မင်္ဂလာပါ"
puts "length: #{word.length}"
puts "bytesize: #{word.bytesize}"
puts "graphemes: #{word.grapheme_clusters.size}"
pair = "ကို"
puts "code points: #{pair.codepoints.map { |c| c.to_s(16) }.inspect}"
puts "after reverse: #{pair.reverse.codepoints.map { |c| c.to_s(16) }.inspect}"The second half shows the danger of reverse. Reversing "ကို" by code point moves the two vowel signs (102f and 102d) in front of the consonant (1000). A vowel sign with no consonant before it is not valid Myanmar text. That is why it matters that reverse_words turns the order of the words and never touches the inside of a single word. Use bytesize for storage limits such as a database column, length for counting code points, and treat anything about on-screen width as an estimate.
In real projects
In real projects
Small functions like these are the daily material of real code reviews: a pricing rule, a report line, a validation helper. What the exercises train is not syntax but anticipation: what does this method do with an empty cart, a missing field, two customers with the same score? Teams capture the answers as tests. The show helper in the reference solution is a tiny version of that habit, and the next step is Minitest (lesson 27), where each call becomes an assertion that fails loudly when behaviour changes.
Text handling is where assumptions cost the most. A signup form that limits names to 20 characters must decide whether it means bytes, code points or visible characters, because Myanmar, emoji and accented text give a different count for each. Database columns, JSON payloads and terminal widths each count differently too.
Common mistakes
Common mistakes
Writing n / 2 == 0 instead of n % 2 == 0
Integer division gives 7 / 2 as 3 and 1 / 2 as 0, so n / 2 == 0 is true only for 0 and 1. even_or_odd(7) happens to look right as "Odd", but even_or_odd(10) also answers "Odd" and even_or_odd(1) answers "Even", both wrong. Use % or even? for the remainder.
Writing split("") instead of split
split("") cuts the string into single characters, so "Ruby is fun".split("").reverse.join gives "nuf si ybuR": the letters were reversed, not the words. split with no argument, or split(" "), separates words. split(/ /) leaves empty strings behind when two spaces touch.
Summing an empty array with reduce(:+)
[].reduce(:+) returns nil rather than 0, because there is no element to start from. Using the result in more arithmetic or formatting then raises NoMethodError. [].sum gives 0, and reduce(0, :+) does too. But [1, nil, 3].sum raises TypeError, so call compact first.
Trusting to_h with duplicate keys
[["Su", 80], ["Su", 60]].to_h returns {"Su" => 60}: the last pair wins and no error appears. In a task that wants the highest score this is simply wrong, and nobody learns the 80 was lost. Decide for yourself how duplicate keys combine (highest, total, or a list of all).
Best practices
Best practices
- Write the promise as a one-line comment first, then add each strange input as a call
- Return values and keep printing at the bottom of the file
- Decide whether nil is skipped, treated like "" or raises, and stay consistent within a method
- When you limit text length, write down whether you mean bytes, code points or visible characters
Mini challenge
Write palindrome?
Write palindrome?(text): true when the text reads the same forwards and backwards, ignoring case, spaces and punctuation. An empty string and a single character are palindromes. nil is not a string, so raise ArgumentError.
- Ignore case and everything that is not a letter or digit (use [[:alnum:]])
- Return true for "" and for one-character strings
- Raise ArgumentError for nil and other non-strings
- Never modify the argument (do not use downcase! or gsub! on it)
def palindrome?(text)
# TODO: raise ArgumentError unless text is a String
# TODO: build a cleaned copy: lower case, only letters and digits
# TODO: compare the copy with its reverse
# (the argument itself must stay unchanged)
endExpected: One line per sample: "Racecar", the Panama sentence, "12321" and "ab ba" give true, "Ruby" gives false, and "" and "x" give true. Then you see that Noon is unchanged, that a frozen string works, and the ArgumentError for nil.
Show hint
downcase returns a new string and leaves the original alone, and so does gsub. gsub(/[^[:alnum:]]/, "") removes everything that is not a letter or digit. This answer is meant for Latin-script text; [[:alnum:]] may not match some combining marks used in Myanmar writing.
Show solution
# True when the text reads the same both ways, ignoring case, spaces and punctuation.
# Written for Latin-script text; it never changes the String it is given.
def palindrome?(text)
raise ArgumentError, "expected a String, got #{text.inspect}" unless text.is_a?(String)
letters = text.downcase.gsub(/[^[:alnum:]]/, "")
letters == letters.reverse
end
samples = ["Racecar", "A man, a plan, a canal: Panama", "Ruby", "", "x", "12321", "ab ba"]
samples.each do |text|
puts "#{text.inspect} -> #{palindrome?(text)}"
end
word = "Noon"
palindrome?(word)
puts "after the call the argument is still #{word.inspect}"
puts "frozen strings work too: #{palindrome?("Level".freeze)}"
begin
palindrome?(nil)
rescue ArgumentError => e
puts "nil -> ArgumentError: #{e.message}"
endQuick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Start each exercise from the signature and the promise, and list strange inputs as extra calls
- Remember that Integer division rounds down in Ruby and that the sign of % follows the divisor
- On an empty array sum gives 0 and reduce(:+) gives nil, and to_h keeps only the last of duplicate keys
- Decide what ties and nil do, and never let the result depend on insertion order
- For Myanmar text, length (code points), bytesize (UTF-8 bytes) and grapheme_clusters.size are different numbers
Official Ruby Documentation — Ruby Documentation