One of the main reasons why we as developers love programming in Ruby is because of the freedom that it gives to us. Having the autonomy to do something is one of the core pillars of motivation. In this article, we will briefly see how you can write a method that you can then call for each of your string objects, prepending an “a” or “an” before words.
According to the English language rule, we will be appending “an” before the words that start with the characters a, e, i, o and u, and “a” before the words that start with other characters.
Here is an implementation of that:
String.class_eval do
def a_or_an
unless self.empty?
if self[0] == self[0].downcase
%w(a e i o u).include?(self[0]) ? "an #{self}" : "a #{self}"
elsif self[0] == self[0].upcase
%w(A E I O u).include?(self[0]) ? "An #{self[0].downcase}#{self[1..-1]}" : "A #{self[0].downcase}#{self[1..-1]}"
end
end
end
end
We are initially testing whether the word is empty. In cases when it is not an empty string, we are moving forward. If the first character starts with a downcase character, then we are checking whether that character is a, e, i, o and u. In cases when this condition is fulfilled, then we add an before the respective word, or a otherwise. This is similar to the case when the word starts with a capital letter, but in this case, we will display the first character of the word after the article (A or An) downcased.
Now if we call this method into string methods, then we can see similar results as below:
<span style="font-weight: 400;">"airplane"</span><span style="font-weight: 400;">.</span><span style="font-weight: 400;">a_or_an</span>
<span style="font-weight: 400;">=></span> <span style="font-weight: 400;">"an airplane"</span>
<span style="font-weight: 400;">"Banana"</span><span style="font-weight: 400;">.</span><span style="font-weight: 400;">a_or_an</span>
<span style="font-weight: 400;">=></span> <span style="font-weight: 400;">"A banana"</span>
There is also a gem that does exactly that, but I wanted to use this article as a way of explaining the very simple logic behind this implementation using Ruby. There is a lot of magic that you can do using Ruby, and hope that this article triggers some sparks of your curiosity about learning and benefiting from it.