# Replacing the vowels of a string with the letter “X”

This code replaces every vowel of the string with "X":

def vowel_censor(sentence)
vowels = "aeiou".chars
result = []
sentence.chars.each do |charachter|
if vowels.include?(charachter)
result << "X"
else
result << charachter
end
end
result.join("")
end

puts "---------Vowel Censor----------"
puts vowel_censor("Let's order a pizza") == "LXt's XrdXr X pXzzX"
puts vowel_censor("Nitwit, blubber, oddment, tweak") == "NXtwXt, blXbbXr, XddmXnt, twXXk"
puts vowel_censor("Supercalifragilisticexpialidocious") == "SXpXrcXlXfrXgXlXstXcXxpXXlXdXcXXXs"


Look into regular expressions, which Ruby is very good at:

def vowel_censor(string)
string.gsub(/[aeiou]/i, "X") # case-insensitive
end


Or, even easier, more low-level and more efficient, use String#tr:

def vowel_censor(string)
string.tr("aeiou", "X") # lowercase only; use "aeiouAEIOU" to handle both upper- and lowercase
end


• The Ruby convention is 2 spaces of indentation. Not 4 spaces, not tabs

• Your code doesn't handle uppercase vowels

• join doesn't need an argument in this case

• charachter is misspelt

• Don't create a variable (result in this case) and modify it from inside a block unless you really, really have to. Do something like this instead:

sentence.chars.reduce([]) do |result, char| # reduce is also aliased as #inject
result << vowels.include?(char) ? "X" : char
end.join


or (building a string instead of an array)

sentence.chars.reduce("") do |result, char|
result += vowels.include?(char) ? "X" : char
end


or (using a method similar to reduce)

sentence.chars.each_with_object([]) do |result, char|
result << vowels.include?(char) ? "X" : char
end.join

• Wow, thank you @Flambino! You are right, using a regular expression in this case is better!! – Joana B Dec 28 '16 at 20:54
• @JoanaB Yeah, regular expressions are incredibly useful, though in this case String#tr does the job just as well, without the (admittedly negligible) overhead of regex. Replacing characters in a string is precisely what tr is built for; using regex is pretty overkill – Flambino Dec 28 '16 at 20:58
• Thank you @Flambino, it's the first time I'm hearing about #tr(it will be very useful from now on). Yes definitely, using #tr is easier than using regular expressions. – Joana B Dec 28 '16 at 21:05
• @JoanaB Yeah, tr is often overlooked - even though it's actually old as dirt: Its name comes from a standard unix/linux command line program also called tr. Don't know when the CLI program appeared but I'm guessing ~40 years ago – Flambino Dec 28 '16 at 21:11
• This is interesting - 40 years is a lot!! I just wished it had another way of handling uppercase letters : ) – Joana B Dec 28 '16 at 21:22