Challenge 1: Saying Hello

Challenge number 1 is a variation of the classic Hello World program; the first thing many programmers learn to do in any language. In this one, the program asks for your name, and then prints a greeting, using the name that’s been entered. As a challenge, it asks you to have the program print a different greeting for different names. I’ve actually already solved challenges 1-6, but I’ve decided to go back and refactor to make the code a bit better, and to try to learn something new along the way.

Before refactoring, I asked the user for their name, capitalized the first letter, and then used a conditional block to choose a greeting. The line to get the name was:

name = gets.chomp.capitalize

Very straightforward, very easy. In thinking about it now, I decided it needed some way to enforce some naming conventions. With the code as-is, users could submit anything they wanted as a name! That won’t do. I decided to create a couple new methods that would enforce a more strict set of rules for names.

With OOP in mind, I started with the has_numeral? Method:

class String

   def has_numeral?

       self.split('').any? { |character| character.to_i.to_s == character}

   end

end

I kinda fumbled around this one for a while, converting strings to arrays, and then crunching the results. I settled on the .any? method applied to the .split method, and then, checks to see if each character is a numeral. The whole thing returns true if there’s a numeral.

Next, I modified the getInteger() method to enforce naming conventions:

def getString(prompt)

   begin

       puts prompt

       string = String(gets.chomp.capitalize)

       raise if string.has_numeral? || string.empty?

   rescue

       puts "Please make an entry, and make sure it's actual letters, Elon!"

       retry

   end

   return string

end

This method uses Raise Exception to trigger the rescue-retry block. The rest of the code is the same as the basic solution; it chooses one of three greetings based on the first initial of the user’s name.

Hopefully you find this interesting! Day 2 of 57 Complete!

Published by corbettbw

I am a Ruby developer in Phoenix, AZ. I'm interested in the intersection of technology and social justice, love weird science facts, and my dog, Coco; a cute black lab/pit bull mix, who won't stop eating rocks.

Leave a comment