ruby coding challenges
# Challenge 1: Calculate the sum of an array
def sum_array(arr)
arr.sum
end
# Challenge 2: Find the maximum number in an array
def max_number(arr)
arr.max
end
# Challenge 3: Reverse a string
def reverse_string(str)
str.reverse
end
# Challenge 4: Check if a string is a palindrome
def palindrome?(str)
str == str.reverse
end
# Challenge 5: Calculate the factorial of a number
def factorial(num)
(1..num).reduce(:*) || 1
end
# Challenge 6: Count the occurrences of each element in an array
def count_occurrences(arr)
arr.each_with_object(Hash.new(0)) { |item, counts| counts[item] += 1 }
end
Explanation:
sum_array(arr)
takes an arrayarr
and uses thesum
method to calculate the sum of all elements in the array.max_number(arr)
takes an arrayarr
and uses themax
method to find the maximum number in the array.reverse_string(str)
takes a stringstr
and uses thereverse
method to reverse the characters in the string.palindrome?(str)
takes a stringstr
and checks if it's a palindrome by comparing the original string with its reversed version.factorial(num)
calculates the factorial of a numbernum
using thereduce
method and the range from 1 tonum
.count_occurrences(arr)
takes an arrayarr
and useseach_with_object
along with a hash to count the occurrences of each element in the array, storing the counts in a hash where keys are the array elements and values are their respective counts.