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:

  1. sum_array(arr) takes an array arr and uses the sum method to calculate the sum of all elements in the array.

  2. max_number(arr) takes an array arr and uses the max method to find the maximum number in the array.

  3. reverse_string(str) takes a string str and uses the reverse method to reverse the characters in the string.

  4. palindrome?(str) takes a string str and checks if it's a palindrome by comparing the original string with its reversed version.

  5. factorial(num) calculates the factorial of a number num using the reduce method and the range from 1 to num.

  6. count_occurrences(arr) takes an array arr and uses each_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.