0
0
Rubyprogramming~5 mins

Pure functions concept in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a pure function?
A pure function is a function that always returns the same result given the same inputs and has no side effects (does not change anything outside itself).
Click to reveal answer
beginner
Why are pure functions important in programming?
Pure functions are important because they are predictable, easier to test, and help avoid bugs caused by changing external data.
Click to reveal answer
intermediate
Which of these is a side effect that a pure function must NOT have?
Changing a global variable, modifying input arguments, or performing input/output like printing to the screen are side effects pure functions must avoid.
Click to reveal answer
beginner
Example: Is this Ruby method pure?
def add(a, b)
  a + b
end
Yes, this method is pure because it always returns the sum of a and b without changing anything else.
Click to reveal answer
intermediate
Example: Is this Ruby method pure?
def add_and_print(a, b)
  sum = a + b
  puts sum
  sum
end
No, this method is not pure because it prints to the screen, which is a side effect.
Click to reveal answer
What does a pure function always guarantee?
ADepends on external data
BSame output for same inputs and no side effects
CPrints output to the screen
DChanges global variables
Which of these is NOT a characteristic of a pure function?
ANo side effects
BReturns a value
CModifies input arguments
DDeterministic output
In Ruby, which method below is pure?
Adef multiply(x, y); x * y; end
Bdef greet(name); puts "Hello, #{name}"; end
Cdef save_to_file(data); File.write('file.txt', data); end
Ddef increment_counter; $counter += 1; end
Why is it easier to test pure functions?
ABecause they depend on external state
BBecause they print output
CBecause they modify global variables
DBecause they always produce the same output for the same input
Which of these is a side effect that breaks purity?
AChanging a global variable
BReturning a calculated value
CUsing local variables
DCalling another pure function
Explain what a pure function is and why it is useful.
Think about functions that behave like a math formula.
You got /4 concepts.
    Give an example of a pure function in Ruby and explain why it is pure.
    Use a simple method like adding two numbers.
    You got /4 concepts.