# [Ruby] How to find the sum of each digit

## Purpose

For example, the number 1,234. The sum of each digit of this number is `1 + 2 + 3 + 4` and the answer is` 10`. There are two ways to output this using Ruby.

## How to use operators

One is to use operators to extract the values ​​of each digit and add them all.

``````
num = 1234

thousand = (num / 1000) % 10   # => 1
hundred = (num / 100) % 10     # => 2
ten = (num / 10) % 10          # => 3
one = num % 10                 # => 4

answer = thousand + hundred + ten + one

# => 10
``````

### Operator used

operator meaning
/ Division(division)
% Surplus(remainder)

### Commentary

First, ** How to get the first digit **. When you want only `4` in the number` 1234` To extract `4` from` 1234`, divide `1234` by` 10` and the remainder will be the ones digit `4`.

``````
1234 ÷ 10 = 123.4   ===>123 ・ ・ ・ 4
``````

You can find this remainder by using the operator `%`.

``````
1234 % 10
# => 4
``````

`%` strips the integer part of the quotient and returns only the remainder.

Next, ** How to get a value with two or more digits **. To find the tens, hundreds, and higher digits, if you can bring the digit of the value you want to find to the ones digit, you can find it by the method of calculating the ones digit above. I can do it. That is, of `1234`

--When you want the tens place, => `123.4` = Truncate after the decimal point =>` 123` --When you want the hundreds digit, => `12.34` = Truncate after the decimal point =>` 12` --When you want the thousands, => `1.234` = Truncate after the decimal point =>` 1`

You can do this by dividing the number by the digit you want to find.

``````
#Tenth place
1234 ÷ 10 = 123.4
#Hundreds
1234 ÷ 100 = 12.34
#Thousands
1234 ÷ 1000 = 1.234
``````

Use `/` for operator division.

``````
#Tenth place
1234 / 10
# => 123

#Hundreds
1234 / 100
# => 12

#Thousands
1234 / 1000
# => 1
``````

`/` removes the decimal point of the quotient and returns only the integer part.

By combining this with the above method of calculating the ones digit value, you can obtain the desired digit value.

``````
#Hundreds
(1234 / 100) % 10
# => 3
``````

All you have to do is add all the calculated values.

## How to use the method

The other is to use a method to make an array of numbers and match them.

``````num = 1234

# => 10
``````

### Method used

Method role
digits Break the numbers apart by place
sum Sum the elements of the array

### Commentary

First, use the `digits` method to split by place. The `digits` method splits by place and returns an array arranged from the first place.

``````1234.digits
# => [4, 3, 2, 1]
``````

Then add each element of the array with the `sum` method.

``````
[4, 3, 2, 1].sum
# => 10
``````

## Finally

If you only want to get the value of each digit, you can calculate with the operator, but if you want to find the sum, it is easier to use the method.

Thank you for visiting.