[RUBY] Extract each digit number from a 3-digit integer

As the title says This is the output of how to extract the hundreds, tens, and ones digits from a three-digit integer.

Hundreds

The remainder of the calculation result of dividing an integer by 100 and then dividing it by 10 is the hundreds digit.

num = 345
result_100 = (num / 100) % 10
puts result_100
# => 3

If you do (num / 100) normally, it will be 3.45, In the case of Ruby, since integer / integer = integer (rounded down to the nearest whole number) (num / 100) becomes 3.

Tenth place

The remainder of the calculation result of dividing an integer by 10 and then dividing it by 10 is the tens digit.

num = 345
result_10 = (num / 10) % 10
puts result_10
# => 4

(num / 10) is 34, and when 34 is divided by 10, the remainder is 4.

First place

The remainder of the calculation result of dividing an integer by 10 is the ones place.

num = 345
result_1 = num % 10
puts result_1
# => 5

bonus

If you want to extract the thousands digit with a 4-digit number It becomes (num / 1000)% 10. Hundreds, tens, and ones are calculated in the same way as above.

Recommended Posts

Extract each digit number from a 3-digit integer
About getting a tens digit with "(two-digit integer) / 10% 10"
How to get an arbitrary digit from a number of 2 or more digits! !!
Extract elements in order from a class type ArrayList
Extract a specific element from the list of objects
[Ruby] How to extract a specific value from an array under multiple conditions [select / each]
Easily get an integer from a system property in Java