Ruby 5 or higher sum of integers

Introduction

Please note that this is a learning note.

This time, we will calculate the sum of integers of 5 or more.

Input example 1
1
3

Output example 1
0


Input example 2
9
2
-3
-3
4
-1
6
4
5
8

Output example 2
19

Source code

loop = gets.chomp.to_i
ans = 0                    //Set initial value

(1..loop).each do |i|
    num = gets.chomp.to_i

    if num >= 5 
        ans = ans + num
    end
end

puts ans

Commentary

loop = gets.chomp.to_i

gets.chomp.to_i gets the first line (9 in Example 2) -Get the input value with the gets method -Chop method: Removes line breaks in character strings. -To_i method: Converts a character string to an integer

(1..loop).each do |i|

The value after 1 of the value assigned to the loop with (1..loop) is repeatedly extracted and the variable i Substituted in (obtain the second and subsequent lines (2 -3 -3 4 -1 6 4 5 8 in Example 2))

num = gets.chomp.to_i

Convert the value assigned to the variable i to an integer again and assign it to num

if num >= 5 
   ans = ans + num
end

Add to ans only when num is 5 or more in the if statement

Finally

I didn't understand why I needed to convert it to an integer again in each statement.

Thank you for your professor!

Recommended Posts

Ruby 5 or higher sum of integers
Basics of Ruby
[Ruby] How to find the sum of each digit
definition of ruby method
Basic methods of Ruby hashes
Basic methods of Ruby arrays
[Ruby] Various types of each
[Ruby] List of basic commands
Judgment of fractions in Ruby
Review of Ruby basic grammar
[Illustration] Finding the sum of coins with a recursive function [Ruby]