Challenge - 5 Problems
Pure Functions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a pure function call
What is the output of this Ruby code that uses a pure function?
Ruby
def multiply_by_two(x) x * 2 end result = multiply_by_two(5) puts result
Attempts:
2 left
💡 Hint
Think about what the function does with the input number.
✗ Incorrect
The function multiply_by_two returns the input number multiplied by 2 without changing anything else. So 5 * 2 equals 10.
🧠 Conceptual
intermediate2:00remaining
Identifying pure functions
Which of the following Ruby methods is a pure function?
Attempts:
2 left
💡 Hint
A pure function always returns the same output for the same input and has no side effects.
✗ Incorrect
Only the square method returns the same output for the same input and does not change anything outside itself.
🔧 Debug
advanced2:00remaining
Why is this function not pure?
This Ruby function looks simple but is not pure. What causes it to be impure?
Ruby
def add_to_list(item, list = []) list << item list end result1 = add_to_list(1) result2 = add_to_list(2) puts result2.inspect
Attempts:
2 left
💡 Hint
Think about what happens to the default list argument when the function is called multiple times.
✗ Incorrect
In Ruby, default arguments are evaluated once. The same list is used in every call, so the function changes external state making it impure.
📝 Syntax
advanced2:00remaining
Which function definition is a pure function?
Select the Ruby function that is syntactically correct and pure.
Attempts:
2 left
💡 Hint
A pure function must not have side effects and must return a value consistently.
✗ Incorrect
Option D returns the sum without side effects. Option D prints output, C changes instance variable, D returns nil if x <= 0.
🚀 Application
expert2:00remaining
Predict the output of a function with external state
What will be printed when this Ruby code runs?
Ruby
def counter @count ||= 0 @count += 1 end puts counter puts counter puts counter
Attempts:
2 left
💡 Hint
Look at how the instance variable @count changes each time the function is called.
✗ Incorrect
The @count variable starts at 0 and increments by 1 each call, so outputs are 1, 2, and 3.