here sum all fibonacci terms that are even: `def fibona(n) return n if n < 2 fib_sequence = [1, 1] (1...n).each do |_| fib_sequence << fib_sequence[-1] + fib_sequence[-2] end fib_sequence end` in ruby

To find the sum of all even Fibonacci terms using the given code in Ruby, you can modify the fibona method to include logic for summing the even terms. Here's an updated version of the code:

main.rb
def fibona(n)
  return n if n < 2
  
  fib_sequence = [1, 1]
  
  (1...n).each do |_|
    next_fib = fib_sequence[-1] + fib_sequence[-2]
    fib_sequence << next_fib
    
    # Add only the even Fibonacci terms to the sum
    fib_sequence[-2] % 2 == 0 ? fib_sequence[-2] : 0
  end
  
  # Calculate the sum of all even Fibonacci terms
  even_sum = fib_sequence.select { |num| num.even? }.sum
  
  even_sum
end
409 chars
19 lines

You can then call the fibona method and pass the desired value of n as an argument:

main.rb
fib_result = fibona(10)
puts fib_result  # Output: 44
54 chars
3 lines

In the above example, n is set to 10, and the resulting sum of the even Fibonacci terms up to the 10th term is printed.

related categories

gistlibby LogSnag