Ruby beginner needs formula help

I’m trying to take user’s input for their birthday and break it down to
a single digit through multiple addition formulas. Example…

2 + 0 + 0 + 8 =10
1 + 0 = 1


2.1.1 :001 > month = gets.chomp.to_f
=> 3.0
2.1.1 :002 > day = gets.chomp.to_f
=> 22.0
2.1.1 :003 > year = gets.chomp.to_f
=> 1983.0
2.1.1 :004 > birth = (month+day+year).to_i
=> 2008

That is as far as I’ve gotten. I can’t break the 2008 to get to the
next step in the formula. Any suggestions?

Well, there are probably a number of ways to approach this, but I’ll show what popped into my head as I read this.

  1. Given the variable birth = 2008, we need to find away to run a method on it to split the numbers apart. One of the best things you can do when learning Ruby is to use the “.class” method. This will tell you what class your variable is.

  2. So, according to the example (as best as I can tell) running birth.class will return Fixnum. Now it’s time to take a look at the Ruby documentation. (

This will give you a list of methods that are available to run on our variable. As you read through the list, you’ll notice that there really isn’t a method to do what we want. (Split the numbers apart so we can add them.)

  1. However, we can convert “birth” to a string with the .to_s method. Now we can take another look at the documentation to see if there is a method that will work for us. (

  2. Conveniently, Ruby has a split method. (

  3. So, this brings us to where we can split the integer with the following:


  1. Now you have an array of the four digits. We need a way to change them back to an integer so that we can perform some addition on them. So we need to check out the Ruby documentation for the Array class. (

  2. Now this part is a little trickier than what we’ve done previously. But we can use the map method to map the array back to an integer


  1. The hardest part is that we do not have a method to add the four parts of the array. So we have to create our own. What you’ll need to do is do some research on the inject method. (

Before I get to the final solution, let me give a few points of summary. First, learn to use “.class” as it will direct you to the documentation that you need to look up. Second, refer to the documentation to find methods that will work on the object that you are working on. Finally, there could be a better way to do this, but as a beginner it is important that you learn to go through a process similar to this to solve programming problems.

Now here’s what the final method chain will look like.

birth.to_s.split(//).map(&:to_i).inject{|sum,x| sum + x }

You’ll do something similar to add the final set of numbers. Hope that helps! :slight_smile:

Awesome! Thank you scannon for helping me and for the links on where I can read up on those methods you used. I did have birth.to_s.split(//) at one point but not the map or inject methods. Thanks again!

Glad to help! :slight_smile: