Bird
0
0

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:
  1. 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.
  2. 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.
  3. Final Answer:

    def double(x); x * 2; end -> Option A
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes