Ruby Practice Exercises: Essential Techniques for Mastering the Framework

Here’s a short practice exercise about Ruby:

Problem:

Write a Ruby program that takes a list of numbers as input and returns the sum of all even numbers in the list.

Example:

rubyCopy codenumbers = [2, 3, 6, 8, 9, 10, 11]
puts sum_even_numbers(numbers) #=> 26

Solution:

rubyCopy codedef sum_even_numbers(numbers)
  sum = 0
  numbers.each do |num|
    if num.even?
      sum += num
    end
  end
  return sum
end

numbers = [2, 3, 6, 8, 9, 10, 11]
puts sum_even_numbers(numbers) #=> 26

In this program, we define a method called sum_even_numbers that takes a list of numbers as input. We then initialize a variable called sum to 0, which we will use to keep track of the sum of all even numbers in the list.

We then iterate over each number in the list using the each method, and check whether the number is even using the even? method. If the number is even, we add it to the sum variable.

Finally, we return the sum variable, which contains the sum of all even numbers in the list. We test our method by passing in a list of numbers and printing the result to the console.

Note: This is just one possible solution to the problem, and there are many other ways to write a Ruby program that solves this task.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *