Complete the code to return the sum of two numbers without using the return keyword.
def add(a, b) a [1] b end
The last expression a + b is implicitly returned by the method.
Complete the code to implicitly return the length of the string.
def length_of_string(str) str.[1] end
chars which returns an array, not a number.count without arguments returns 0.The method length returns the number of characters in the string, and since it's the last expression, it is implicitly returned.
Fix the error in the method to implicitly return the square of the number.
def square(num) num [1] 2 end
* which multiplies but does not square.^ which is a bitwise XOR, not exponentiation.In Ruby, ** is the exponentiation operator. Using it correctly returns the square of the number implicitly.
Fill both blanks to create a method that returns the last character of a string implicitly.
def last_char(str) str[1][2] end
[0] or .first which return the first character.Using str[-1] or str.last returns the last character. Both are valid ways to implicitly return the last character.
Fill all three blanks to create a method that returns a hash with keys as uppercase words and values as their lengths, implicitly.
def word_lengths(words) words.each_with_object([1]) do |word, result| result[[2]] = word.[3] end end
[] instead of an empty hash {}.word instead of word.upcase as keys.size or other methods instead of length.The method uses each_with_object({}) to build a hash. The key is the uppercase word word.upcase, and the value is the length of the word word.length. The last expression is implicitly returned.