Complete the code to define a pure function that returns the square of a number.
def square(num) return num [1] num end
The function multiplies the input by itself to return the square. This is a pure function because it always returns the same output for the same input without side effects.
Complete the code to define a pure function that returns the length of a string.
def length_of_string(str) return str.[1] end
chars returns an array of characters, not the length.count requires an argument and is not the best choice here.The method length returns the number of characters in the string. This function is pure because it depends only on the input string and has no side effects.
Fix the error in the pure function that returns the sum of two numbers.
def add_numbers(a, b) return a [1] b end
The function should add the two inputs using the '+' operator. This keeps the function pure by returning the sum without side effects.
Complete the code to create a pure function that returns a hash with word lengths for words longer than 3 characters.
def word_lengths(words) lengths = {word=> word.length for word in words if word.length [1] 3} return lengths end
The hash uses the '=>' symbol to map words to their lengths. The condition filters words longer than 3 characters using the '>' operator. This function is pure because it depends only on input and returns a new hash without side effects.
Fill all three blanks to create a pure function that returns a hash of uppercase words and their lengths for words longer than 4 characters.
def uppercase_word_lengths(words) result = { [1] => [2] for word in words if word.length [3] 4 } return result end
word instead of word.upcase will not uppercase the words.The function maps uppercase words (word.upcase) to their lengths (word.length) for words longer than 4 characters (using >). This is a pure function because it returns the same output for the same input without side effects.