Recall & Review
beginner
What is a pure function?
A pure function is a function that always returns the same result given the same inputs and has no side effects (does not change anything outside itself).
Click to reveal answer
beginner
Why are pure functions important in programming?
Pure functions are important because they are predictable, easier to test, and help avoid bugs caused by changing external data.
Click to reveal answer
intermediate
Which of these is a side effect that a pure function must NOT have?
Changing a global variable, modifying input arguments, or performing input/output like printing to the screen are side effects pure functions must avoid.
Click to reveal answer
beginner
Example: Is this Ruby method pure?
def add(a, b) a + b end
Yes, this method is pure because it always returns the sum of a and b without changing anything else.
Click to reveal answer
intermediate
Example: Is this Ruby method pure?
def add_and_print(a, b) sum = a + b puts sum sum end
No, this method is not pure because it prints to the screen, which is a side effect.
Click to reveal answer
What does a pure function always guarantee?
✗ Incorrect
Pure functions always return the same result for the same inputs and do not cause side effects.
Which of these is NOT a characteristic of a pure function?
✗ Incorrect
Pure functions do not modify their input arguments.
In Ruby, which method below is pure?
✗ Incorrect
Only the multiply method is pure because it returns a value without side effects.
Why is it easier to test pure functions?
✗ Incorrect
Pure functions are easier to test since their output depends only on their input.
Which of these is a side effect that breaks purity?
✗ Incorrect
Changing a global variable is a side effect and breaks the purity of a function.
Explain what a pure function is and why it is useful.
Think about functions that behave like a math formula.
You got /4 concepts.
Give an example of a pure function in Ruby and explain why it is pure.
Use a simple method like adding two numbers.
You got /4 concepts.