Bird
0
0

Which Ruby code snippet correctly defines a pure function that returns the cube of a number without altering any external variables?

easy📝 Syntax Q3 of 15
Ruby - Functional Patterns in Ruby
Which Ruby code snippet correctly defines a pure function that returns the cube of a number without altering any external variables?
Adef cube(x); x ** 3; @last = x; end
Bdef cube(x); @result = x * x * x; end
Cdef cube(x); x * x * x; end
Ddef cube(x); puts x * x * x; end
Step-by-Step Solution
Solution:
  1. Step 1: Identify pure function characteristics

    A pure function returns a value based only on its inputs and does not modify external state.
  2. Step 2: Analyze each option

    def cube(x); x * x * x; end returns the cube of x without side effects. Options B and C modify instance variables, and D outputs to console.
  3. Final Answer:

    def cube(x); x * x * x; end -> Option C
  4. Quick Check:

    Pure functions avoid side effects and external state changes. [OK]
Quick Trick: Pure functions do not modify external state. [OK]
Common Mistakes:
  • Using instance variables inside the function.
  • Printing output instead of returning a value.
  • Modifying external variables within the function.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes