HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMajor

It'th wabbit theathon

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wabbittheathonstackoverflow

Problem

I don't know regex. I want to learn regex, but learning regex just for the sake of regex would be quite boring.

So I decided to learn Ruby as well (which so far looks a lot like Python, which I'm familiar with).

My first program attempts to speak with a combination of both Daffy Duck's lisp and Elmer Fudd's verbal apraxia.

It works quite well, but it looks quite messy already. How does one properly combine Ruby and (repeated) regex substitutions?

def lisp(input)
   return input.downcase.gsub(/s/, "th").gsub(/er/, "uh").gsub(/r|l/, "w").capitalize
end

print lisp("What's your input?")
user_input = gets.chomp

puts lisp(user_input)


I downcase everything to make the regex easier and capitalize at the end to turn it back into a proper sentence.

Usage:

What'th youw input? It's rabbit season!



It'th wabbit theathon!

What'th youw input? My super soaker carries 2 liters of water!



My thupuh thoakuh cawwieth 2 wituhth of watuh!

Solution

In general, it is bad practice to perform string substitutions in multiple passes, feeding the output back of one substitution into another round of substitutions. (Here is an example of how multiple-pass substitutions can lead to incorrect results.) In this case, it happens to be safe, since none of the outputs overlap with any of the patterns, but I would still recommend a different approach. Fortunately, Ruby makes it easy to do multiple substitutions the right way, with #gsub(pattern, hash).

return is implicit in Ruby. The last expression evaluated is automatically returned, and everything is an expression.

The standard is to use two spaces of indentation, not three.

def lisp(input)
  input.downcase.gsub(/er|[lrs]/,
    'er' => 'uh',
    'l'  => 'w',
    'r'  => 'w',
    's'  => 'th',
  ).capitalize
end

Code Snippets

def lisp(input)
  input.downcase.gsub(/er|[lrs]/,
    'er' => 'uh',
    'l'  => 'w',
    'r'  => 'w',
    's'  => 'th',
  ).capitalize
end

Context

StackExchange Code Review Q#112329, answer score: 35

Revisions (0)

No revisions yet.