Let's solve another problem.
WARNING: You will probably feel frustrated at solving these coding challenges - they can become quite difficult!
Given a number, write a method called square_each_digit
to find out the square of each digit of the input. If the input is not a number, the program should return "NaN".
For example, 3211
should turn into 9411
, 654326
to 3625169436
, and "hello"
should return "NaN"
.
Getting Started
First, navigate to the
square_each_digit
directory that you have downloaded in the previous lesson:If you are on
string_compressor
directory, go back one step:cd ..
And navigate to
square_each_digit
directory:cd square_each_digit
Once you are in the folder in the terminal, run the following command:
rspec square_each_digit.rb
This will run some tests to see if your code is working. Since you haven't written any code yet, you will see that all of the tests fail. The output should look something like this:
Next, open up your text editor and open
square_each_digit.rb
You should see code like this:
def square_each_digit num # Write your code here end describe "#square_each_digit" do context "it is a number" do it "returns square of each digit" do expect(square_each_digit(3211)).to eq(9411) expect(square_each_digit(654326)).to eq(3625169436) expect(square_each_digit(1111)).to eq(1111) end end context "it is not a number" do it "returns NaN" do expect(square_each_digit("hello")).to eq("NaN") expect(square_each_digit("12hello")).to eq("NaN") end end end
For now you can ignore following codes:
describe "#square_each_digit" do context "it is a number" do it "returns square of each digit" do expect(square_each_digit(3211)).to eq(9411) expect(square_each_digit(654326)).to eq(3625169436) expect(square_each_digit(1111)).to eq(1111) end end context "it is not a number" do it "returns NaN" do expect(square_each_digit("hello")).to eq("NaN") expect(square_each_digit("12hello")).to eq("NaN") end end end
Implement your solution in this file.
Once you have implemented the solution, go into your terminal and run this command again:
rspec
If your solution is correct, you should see an output like this:
Good luck!