0
0
Rubyprogramming~20 mins

Pure functions concept in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Pure Functions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A10
B5
Cnil
DError
Attempts:
2 left
💡 Hint
Think about what the function does with the input number.
🧠 Conceptual
intermediate
2:00remaining
Identifying pure functions
Which of the following Ruby methods is a pure function?
A
def add_random(x)
  x + rand(10)
end
B
def square(x)
  x * x
end
C
def increment_counter(x)
  $counter += 1
  x + $counter
end
D
def print_value(x)
  puts x
  x
end
Attempts:
2 left
💡 Hint
A pure function always returns the same output for the same input and has no side effects.
🔧 Debug
advanced
2: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
AThe function returns a list which is mutable, so it is impure.
BThe function uses puts which is a side effect.
CThe default list argument is shared between calls, causing side effects.
DThe function does not return a value explicitly.
Attempts:
2 left
💡 Hint
Think about what happens to the default list argument when the function is called multiple times.
📝 Syntax
advanced
2:00remaining
Which function definition is a pure function?
Select the Ruby function that is syntactically correct and pure.
A
def add(x, y)
  x + y
  puts "Sum calculated"
end
B
def add(x, y)
  return x + y if x &gt; 0
end
C
def add(x, y)
  @sum = x + y
end
D
def add(x, y)
  x + y
end
Attempts:
2 left
💡 Hint
A pure function must not have side effects and must return a value consistently.
🚀 Application
expert
2: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
A
1
2
3
B
0
1
2
C
1
1
1
DError: undefined method or variable
Attempts:
2 left
💡 Hint
Look at how the instance variable @count changes each time the function is called.