Which Ruby syntax correctly defines a pure function that doubles a number without changing any external state?
easy📝 Syntax Q12 of 15
Ruby - Functional Patterns in Ruby
Which Ruby syntax correctly defines a pure function that doubles a number without changing any external state?
Adef double(x); x * 2; end
Bdef double(x); @value = x * 2; end
Cdef double(x); puts x * 2; end
Ddef double(x); x *= 2; nil; end
Step-by-Step Solution
Solution:
Step 1: Identify pure function characteristics
A pure function returns a value based only on input and does not change external variables or produce side effects.
Step 2: Check each option
def double(x); x * 2; end returns x * 2 without changing anything else. def double(x); @value = x * 2; end changes an instance variable (@value), so it has side effects. def double(x); puts x * 2; end prints output (side effect). def double(x); x *= 2; nil; end modifies x locally but returns nil, so it doesn't return the doubled value.
Final Answer:
def double(x); x * 2; end -> Option A
Quick Check:
Pure function returns value only [OK]
Quick Trick:Pure functions return values without side effects [OK]
Common Mistakes:
Using instance variables inside pure functions
Printing inside functions instead of returning
Not returning the computed value explicitly
Master "Functional Patterns in Ruby" in Ruby
9 interactive learning modes - each teaches the same concept differently