[Ruby] How to find the sum of each digit


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 -How to use methods such as split

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

p answer
# => 10

Operator used

operator meaning
+ Addition(addition)
/ Division(division)
% Surplus(remainder)


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
1234 ÷ 100 = 12.34
1234 ÷ 1000 = 1.234

Use / for operator division.

#Tenth place
1234 / 10
# => 123

1234 / 100
# => 12

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.

(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
answer = num.digits.sum

p answer
# => 10

Method used

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


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

# => [4, 3, 2, 1]

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

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


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.

Recommended Posts

[Ruby] How to find the sum of each digit
How to find the cause of the Ruby error
Iterative processing of Ruby using each method (find the sum from 1 to 10)
How to find the average angle
[Ruby] How to retrieve the contents of a double hash
How to determine the number of parallels
[Rails] How to change the page title of the browser for each page
How to sort the List of SelectItem
How to find the tens and ones
How to output the sum of any three numbers, excluding the same value
How to switch the display of the header menu for each transition page
How to find out the Java version of a compiled class file
How to find the total number of pages when paging in Java
How to solve the local environment construction of Ruby on Rails (MAC)!
[Ruby On Rails] How to search the contents of params using include?
Customize how to divide the contents of Recyclerview
The story of introducing Ajax communication to ruby
How to get today's day of the week
Output of how to use the slice method
[Ruby] Code to display the day of the week
How to display the result of form input
How to find the total score and average score
How to build the simplest blockchain in Ruby
[Java] How to get the authority of the folder
[Ruby basics] How to use the slice method
[Ruby on Rails] How to make the link destination part of the specified id
How to display the amount of disk used by Docker container for each container
[Ruby on Rails] Rails tutorial Chapter 14 Summary of how to implement the status feed
[Ruby] Meaning of &. How to avoid the error when the receiver (object) is nil
[Ruby on Rails] How to Japaneseize the error message of Form object (ActiveModel)
[Java] How to get the URL of the transition source
How to delete / update the list field of OneToMany
How to write Scala from the perspective of Java
[Ruby on Rails] How to change the column name
How to install the root certificate of Centos7 (Cybertrust)
[Java] How to get the maximum value of HashMap
[Rails] How to change the column name of the table
[SwiftUI] How to specify the abbreviated position of Text
[Android] How to get the setting language of the terminal
[Rails] How to get the contents of strong parameters
How to judge the click of any area of the image
How to download the old version of Apache Tomcat
[Ruby] How to get the tens place and the ones place
[Swift] How to get the document ID of Firebase
How to find the total value, average value, etc. of a two-dimensional array (multidimensional array)-java
Offline real-time how to write Implementation example of the problem in E05 (ruby, C11)
How to request by passing an array to the query with HTTP Client of Ruby
[ruby] How to assign a value to a hash by referring to the value and key of another hash
How to use Ruby return
[Ruby] How to comment out
Ruby: How to use cookies
[Ruby] How to write blocks
[Ruby] How to split each GraphQL query into a file
Difference between Java and JavaScript (how to find the average)
[Ruby] Find a permutation consisting of 0 to 9 at high speed.
Comparison of how to write Callback function (Java, JavaScript, Ruby)
How to retrieve the hash value in an array in Ruby
How to get the longest information from Twitter as of 12/12/2016
How to change the setting value of Springboot Hikari CP
I tried to summarize the basic grammar of Ruby briefly
How to add elements without specifying the length of the array