I am trying to create a program where two strings are entered. If they match it returns the number of positions where they contain the same length 2 substring.
for example:string_match('xxcaazz', 'xxbaaz') → 3 "xx" "aa" "az"
My question is what metacharacters should i use to validate
here is what i have come up with
puts "enter word"
a = STDIN.gets
a.chomp!
puts"enter word"
b = STDIN.gets
b.chomp!
if a == /word/ or b == /word/ then
puts str.match(/{a} {b}/) + "equal"
end
UPDATED ANSWER:
( Still spiked, but better )
first_word = 'xxcaazz'.split('')
second_word ='xxbaaz'.split('')
first_word_length = first_word.length
second_word_length = second_word.length
if [first_word_length, second_word_length].min == first_word_length
inner_word = second_word
outter_word = first_word
else
inner_word = first_word
outter_word = second_word
end
outter_word_length = outter_word.length - 2
word_matches = 0
(0..outter_word_length).each do |character|
if "#{outter_word[character]}#{outter_word[character + 1]}" == "#{inner_word[character]}#{inner_word[character + 1]}"
puts "#{outter_word[character]}#{outter_word[character + 1]}"
word_matches += 1
end
end
puts "Found #{word_matches} matches"
ORIGINAL SPIKE:
This may get you off to a good start ( though it's by no means bullet proof, just a quick spike ):
first_word = 'xxcaazz'.split('')
second_word ='xxbaaz'.split('')
first_word_length = first_word.length
(0..first_word_length).each do |character|
if "#{second_word[character]}#{second_word[character + 1]}" == "#{first_word[character]}#{first_word[character + 1]}"
puts "#{second_word[character]}#{second_word[character + 1]}"
end
end
Unpack 'a2X' means extract the 2 bytes, then rewind 1 byte:
first_word = 'xxcaazz'
second_word ='xxbaaz'
tokens = first_word.unpack 'a2X' * (first_word.length - 1)
# => ["xx", "xc", "ca", "aa", "az", "zz"]
tokens.flat_map{|m| second_word.scan m}
# => ["xx", "aa", "az"]
Related
Write a method that returns the no of various lowercase, uppercase, digits and special characters used in the string. Make use of Ranges.
Input = "heLLo Every1"
I am making using of ranges and case method in solution provided.
Solution:
class String
def character_count
uppercase_count = 0
lowercase_count = 0
digit_count = 0
uppercase_range = Range.new('A', 'Z')
lowercase_range = Range.new('a', 'z')
digit_range = Range.new('0', '9')
special_character_count = 0
each_char do |item|
case item
when uppercase_range
uppercase_count += 1
when lowercase_range
lowercase_count += 1
when digit_range
digit_count += 1
else
special_character_count += 1
end
end
[lowercase_count, uppercase_count, digit_count, special_character_count]
end
end
if ARGV.empty?
puts 'Please provide an input'
else
string = ARGV[0]
count_array = string.character_count
puts "Lowercase characters = #{count_array[0]}"
puts "Uppercase characters = #{count_array[1]}"
puts "Numeric characters = #{count_array[2]}"
puts "Special characters = #{count_array[3]}"
end
Code is working.
Yes
class String
def character_count
counters = Hash.new(0)
each_char do |item|
case item
when 'A'..'Z'
counters[:uppercase] += 1
when 'a'..'z'
counters[:lowercase] += 1
when '0'..'9'
counters[:digit] += 1
else
counters[:special] += 1
end
end
counters.values_at(:uppercase, :lowercase, :digit, :special)
end
end
if ARGV.empty?
puts 'Please provide an input'
else
string = ARGV[0]
uppercase, lowercase, digit, special = string.character_count
puts "Lowercase characters = #{lowercase}"
puts "Uppercase characters = #{uppercase}"
puts "Numeric characters = #{digit}"
puts "Special characters = #{special}"
end
You can instead use regex in better way as following,
type = { special: /[^0-9A-Za-z]/, numeric: /[0-9]/, uppercase: /[A-Z]/, lowercase: /[a-z]/ }
'Hello World'.scan(type[:special]).count
# => 1
'Hello World'.scan(type[:numeric]).count
# => 0
'Hello World'.scan(type[:uppercase]).count
# => 2
'Hello World'.scan(type[:lowercase]).count
# => 8
Other option.
First, map your ranges into an Hash:
mapping = { upper: ('A'..'Z'), lower: ('a'..'z'), digits: ('0'..'9'), specials: nil }
Then initialize the recipient Hash to default 0:
res = Hash.new(0)
Finally, map the chars of the input:
input = "heLLo Every1"
input.chars.each { |e| res[(mapping.find { |k, v| v.to_a.include? e } || [:specials]).first ] += 1 }
res
#=> {:upper=>3, :lower=>7, :digits=>1, :specials=>1}
str = "Agent 007 was on the trail of a member of SPECTRE"
str.each_char.with_object(Hash.new(0)) do |c,h|
h[ case c
when /\d/ then :digit
when /\p{Lu}/ then :uppercase
when /\p{Ll}/ then :downcase
else :special
end
] += 1
end
end
#=> {:uppercase=>8, :downcase=>28, :special=>10, :digit=>3}
I'm writing a program which takes input, stores it as a hash and sorts the values.
I'm having trouble comparing a current hash value with a variable.
Sample Input:
3
A 1
B 3
C 5
A 2
B 7
C 2
Sample Output:
A 1 2
B 3 7
C 2 5
Everything works apart from this part, and I'm unsure why.
if values.key?(:keys)
if values[keys] >= val
values.store(keys,val.prepend(val + " "))
else
values.store(keys,val.concat(" " + val))
end
else
values.store(keys,val)
end
i = i + 1
end
Rest of code:
#get amount of records
size = gets.chomp
puts size
size = size.to_i
values = Hash.new(0)
i = 0
while i < (size * 2)
text = gets.chomp
#split string and remove space
keys = text.split[0]
val = text.split[1]
#check if key already exists,
# if current value is greater than new value append new value to end
# else put at beginning of current value
if values.key?(:keys)
if values[keys] >= val
values.store(keys,val.prepend(val + " "))
else
values.store(keys,val.concat(" " + val))
end
else
values.store(keys,val)
end
i = i + 1
end
#sort hash by key
values = values.sort_by { |key, value| key}
#output hash values
values.each{|key, value|
puts "#{key}:#{value}"
}
Could anyone help me out? It would be most appreciated.
The short answer is that there are two mistakes in your code. Here is the fixed version:
if values.key?(keys)
if values[keys] >= val
values.store(keys,values[keys].prepend(val + " "))
else
values.store(keys,values[keys].concat(" " + val))
end
else
values.store(keys,val)
end
The if statement was always evaluating as false, because you were looking for hash key named :keys (which is a Symbol), not the variable you've declared named keys.
Even with that fixed, there was a second hidden bug: You were storing a incorrect new hash value. val.concat(" " + val) would give you results like A 2 2, not A 1 2, since it's using the new value twice, not the original value.
With that said, you code is still very confusing to read... Your variables are size, i, text, val, values, key and keys. It would have been a lot easier to understand with clearer variable names, if nothing else :)
Here is a slightly improved version, without changing the overall structure of your code:
puts "How may variables to loop through?"
result_length = gets.chomp.to_i
result = {}
puts "Enter #{result_length * 2} key-value pairs:"
(result_length * 2).times do
input = gets.chomp
input_key = input.split[0]
input_value = input.split[1]
#check if key already exists,
# if current value is greater than new value append new value to end
# else put at beginning of current value
if result.key?(input_key)
if result[input_key] >= input_value
result[input_key] = "#{input_value} #{result[input_key]}"
else
result[input_key] = "#{result[input_key]} #{input_value}"
end
else
result[input_key] = input_value
end
end
#sort hash by key
result.sort.to_h
#output hash result
result.each{|key, value|
puts "#{key}:#{value}"
}
h = Hash.new { |h,k| h[k] = [] }
input = ['A 1', 'B 3', 'C 5', 'A 2', 'B 7', 'C 2'].join("\n")
input.each_line { |x| h[$1] << $2 if x =~ /^(.*?)\s+(.*?)$/ }
h.keys.sort.each do |k|
puts ([k] + h[k].sort).join(' ')
end
# A 1 2
# B 3 7
# C 2 5
This would be a more Ruby-ish way to write your code :
input = "A 1
B 3
C 5
A 2
B 7
C 2"
input.scan(/[A-Z]+ \d+/)
.map{ |str| str.split(' ') }
.group_by{ |letter, _| letter }
.each do |letter, pairs|
print letter
print ' '
puts pairs.map{ |_, number| number }.sort.join(' ')
end
#=>
# A 1 2
# B 3 7
# C 2 5
I need to count the number of vowels,words,pronouns("he,she,them") in each line of a string entered by user. if input is "they are playing. he is studying" the output expected is Sentence 1 has 3 words,has 4 vowels , 1 pronoun. \nSentence 2 has 3 words,4 vowels , 1 pronoun. I have written the following code but getting an error unexpected-end-of-input.
string = gets
string =string.chomp
sentencecount = 0
wordcount = 0
pronouns={"He"=>0,"She"=>0,"They"=>0,"Them"=>0}
procount=0;
string.split(".").each do |sentence|
wordcount = 0
sentencecount += 1 #tracking number of sentences
vowels=sentence.scan(/[aeoui]/).count
procount=0
sentence.split(/\w+/).each do |word|
pronouns.each do|key,value|
if (key.eq word)
procount++
wordcount += 1 # tracking number of words
end
puts "Sentence #{sentencecount} has #{wordcount} words, has #{vowels} vowels"
end
you don't need semicolon at the end of the lines
if requires an end (unless it's the inline form)
++ operator doesn't exist in Ruby
you compare two strings with the == operator (it's a method actually)
string = gets.chomp
sentencecount = 0
wordcount = 0
pronouns = {"He"=>0, "She"=>0, "They"=>0, "Them"=>0}
procount = 0
string.split(".").each do |sentence|
wordcount = 0
sentencecount += 1 #tracking number of sentences
vowels = sentence.scan(/[aeoui]/).count
procount = 0
sentence.split(/\w+/).each do |word|
pronouns.each do|key, value|
if key == word
procount += 1
end
wordcount += 1 # tracking number of words
end
end
puts "Sentence #{sentencecount} has #{wordcount} words, has #{vowels} vowels"
end
Based off of your initial attempt, I've optimized it slightly and make it more readable in terms of code.
string = gets.chomp
pronouns = ['he', 'she', 'they', 'them']
total_word_count = 0
total_procount = 0
total_vowel_count = 0
sentences = string.split(".")
total_sentence_count = sentences.size
sentences.each_with_index do |sentence, idx|
# VOWELS
vowel_count = sentence.scan(/[aeoui]/).count
total_vowel_count += vowel_count
# WORDS
words = sentence.split
sentence_word_count = words.size
total_word_count += sentence_word_count
# PRONOUNS
sentence_procount = 0
words.each do |word|
sentence_procount += 1 if pronouns.include?(word.downcase)
end
total_procount += sentence_procount
puts "Sentence #{idx + 1} has #{sentence_word_count} words, has #{vowel_count} vowels"
end
puts "Input has #{total_sentence_count} sentences, #{total_word_count} words, #{total_vowel_count} vowels, and #{total_procount} pronouns"
I suggest you return an array of hashes, one for each line, each hash containing statistics for the associated line. You can then do what you want with the information in that array.
VOWELS = 'aeiou'
PRONOUNS = %w| he she they them |
#=> ["he", "she", "they", "them"]
PRONOUN_REGEX = /\b#{Regexp.union(PRONOUNS)}\b/
#=> /\b(?-mix:he|she|they|them)\b/
def count_em(str)
str.downcase.split(/\n/).map { |line|
{ vowels: line.count(VOWELS),
words: line.scan(/[[:lower:]]+/).count,
pronouns: line.scan(PRONOUN_REGEX).size } }
end
a = count_em "He thought that she thought that he did not know the truth\n" +
"René knew she would torment them until they went bananas\n"
#=> [{:vowels=>14, :words=>12, :pronouns=>3},
# {:vowels=>15, :words=>10, :pronouns=>3}]
a.each.with_index(1) { |h,i|
puts "In line #{i} there are %d vowels, %d words and %d pronouns" %
h.values_at(:vowels, :words, :pronouns) }
# In line 1 there are 14 vowels, 12 words and 3 pronouns
# In line 2 there are 15 vowels, 10 words and 3 pronouns
puts "The total number of vowels in all lines is %d" %
a.map { |h| h[:vowels] }.reduce(:+)
# The total number of vowels in all lines is 29
This solution is incomplete in that it doesn't deal with contractions ("don't"), possessives ("Mary's"), abbreviations ("1st"), initials and numeric parts of names ("J. Philip ('Phil') Sousa III") and other twists of the English language.
I am attempting to write a ruby function that takes in a string of words and turns it into Pig Latin. I am breaking the string into an array, and attempting to iterate over each element. When "eat pie" is put in, the result is "eat ie", but I am unsure why.
string = "eat pie"
array = string.split(" ")
array.map do |word|
if word[0].chr == "a" || word[0].chr == "e" || word[0].chr == "i" || word[0].chr == "o" || word[0].chr == "u"
word = word + "ay"
elsif word[1].chr == "a" || word[1].chr == "i" || word[1].chr == "o" || word[1].chr == "u"
temp = word[0]
word[0] = ""
word = word + temp
word = word + "ay"
elsif word[2].chr == "a" || word[2].chr == "i" || word[2].chr == "o" || word[2].chr == "u"
temp = word[0] + word[1]
word[0] = ""
word[0] = ""
word = word + temp
word = word + "ay"
else ## three consonants
temp = word[0] + word[1] + word[2]
word[0] = ""
word[0] = ""
word[0] = ""
word = word + temp
word = word + "ay"
end ## end of if statement
end ## end of iteration
puts array.join(" ")
Agree with the other answers supplied, here's a slightly less verbose version of your code in case it helps you.
input = 'pig latin is awesome'
arr = input.split(' ').map do |wrd|
if %w(a e i o u).include? wrd[0]
wrd + 'ay'
elsif %w(a i o u).include? wrd[1]
wrd[1..-1] + wrd[0] + 'ay'
elsif %w(a i o u).include? wrd[2]
wrd[2..-1] + wrd[0] + wrd[1] + 'ay'
else
wrd[3..-1] + wrd[0] + wrd[1] + wrd[2] + 'ay'
end
end.join(' ')
puts arr
The output you are seeing has 2 different causes:
1) In Ruby, Array.map returns a new array. It does not modify the array its iterating over. This is causing some of your modifications to the array to be lost.
From the Ruby docs:
Invokes the given block once for each element of self.
Creates a new array containing the values returned by the block.
You should either assign the result to a new variable, or use Array.map! instead, which will modify the contents of the array.
array = string.split(" ")
mapped = array.map do |word|
# ...
end
mapped.join(" ")
2) Although some of your modifications are being lost due to using map, you are making modifications to some strings in your array, which is why you are seeing eat ie, and not eat pie (missing a p).
To illustrate this problem, look a the follow code:
word = "pie"
word[0] = ""
puts word #=> "ie"
In Ruby, when you access the first character in a string (by using [0]), and assign a value to it, Ruby mutates that string, and does not return a new copy.
You should create a new string, instead of changing characters directly:
array.map do |word|
new_word = word.slice(1, word.length)
end
array.map does is not intended to mutate the array, so what you want to do is either newarray = array.map { ... } or array.map! do ... end.
Inside the loop, each word is a string object, that you are mutating by calling word[0] = "". By calling word = word + "ay" you are discarding the reference of the original string, but not overwriting it. It happens though that word = word + "ay" is the last statement executed in the block so it counts as return value for the block.
I bet you are still confused because overall is not that simple so you might probably want to read something about mutable and immutable objects and functional and imperative programming.
Trying to write Method in ruby that will translate a string in pig-latin , the rule :
Rule 1: If a word begins with a vowel sound, add an "ay" sound to the end of the word.
Rule 2: If a word begins with a consonant sound, move it to the end of the word, and then add an "ay" sound to the end of the word and also when the word begins with 2 consonants , move both to the end of the word and add an "ay"
As a newbie , my prob is the second rule , when the word begin with only one consonant it work , but for more than one , I have trouble to make it work ,Can somebody look at the code and let me know how i can code that differently and probably what is my mistake , probably the code need refactoring. Thanks , so far i come up with this code :
def translate (str)
str1="aeiou"
str2=(/\A[aeiou]/)
vowel = str1.scan(/\w/)
alpha =('a'..'z').to_a
con = (alpha - vowel).join
word = str.scan(/\w/)
if #first rule
str =~ str2
str + "ay"
elsif # second rule
str != str2
s = str.slice!(/^./)
str + s + "ay"
elsif
word[0.1]=~(/\A[con]/)
s = str.slice!(/^../)
str + s + "ay"
else
word[0..2]=~(/\A[con]/)
s = str.slice!(/^.../)
str + s + "ay"
end
end
translate("apple") should == "appleay"
translate("cherry") should == "errychay"
translate("three") should == "eethray"
No need for all those fancy regexes. Keep it simple.
def translate str
alpha = ('a'..'z').to_a
vowels = %w[a e i o u]
consonants = alpha - vowels
if vowels.include?(str[0])
str + 'ay'
elsif consonants.include?(str[0]) && consonants.include?(str[1])
str[2..-1] + str[0..1] + 'ay'
elsif consonants.include?(str[0])
str[1..-1] + str[0] + 'ay'
else
str # return unchanged
end
end
translate 'apple' # => "appleay"
translate 'cherry' # => "errychay"
translate 'dog' # => "ogday"
This will handle multiple words, punctuation, and words like 'queer' = 'eerquay' and 'school' = 'oolschay'.
def translate (sent)
vowels = %w{a e i o u}
sent.gsub(/(\A|\s)\w+/) do |str|
str.strip!
while not vowels.include? str[0] or (str[0] == 'u' and str[-1] == 'q')
str += str[0]
str = str[1..-1]
end
str = ' ' + str + 'ay'
end.strip
end
okay this is an epic pig latin translator that I'm sure could use a bit of refactoring, but passes the tests
def translate(sent)
sent = sent.downcase
vowels = ['a', 'e', 'i', 'o', 'u']
words = sent.split(' ')
result = []
words.each_with_index do |word, i|
translation = ''
qu = false
if vowels.include? word[0]
translation = word + 'ay'
result.push(translation)
else
word = word.split('')
count = 0
word.each_with_index do |char, index|
if vowels.include? char
# handle words that start with 'qu'
if char == 'u' and translation[-1] == 'q'
qu = true
translation = words[i][count + 1..words[i].length] + translation + 'uay'
result.push(translation)
next
end
break
else
# handle words with 'qu' in middle
if char == 'q' and word[i+1] == 'u'
qu = true
translation = words[i][count + 2..words[i].length] + 'quay'
result.push(translation)
next
else
translation += char
end
count += 1
end
end
# translation of consonant words without qu
if not qu
translation = words[i][count..words[i].length] + translation + 'ay'
result.push(translation)
end
end
end
result.join(' ')
end
So this will give the following:
puts translate('apple') # "appleay"
puts translate("quiet") # "ietquay"
puts translate("square") # "aresquay"
puts translate("the quick brown fox") # "ethay ickquay ownbray oxfay"
def translate(sentence)
sentence.split(" ").map do |word|
word = word.gsub("qu", " ")
word.gsub!(/^([^aeiou]*)(.*)/,'\2\1ay')
word = word.gsub(" ", "qu")
end
end
That was fun! I don't like the hack for qu, but I couldn't find a nice way to do that.
So for this pig latin clearly I skipped and\an\in and singular things like a\I etc. I know that wasn't the main question but you can just leave out that logic if it's not for your use case. Also this goes for triple consonants if you want to keep it with one or two consonants then change the expression from {1,3} to {1,2}
All pig latin is similar so just alter for your use case. This is a good opportunity to use MatchData objects. Also vowel?(first_letter=word[0].downcase) is a style choice made to be more literate so I don't have to remember that word[0] is the first letter.
My answer is originally based off of Sergio Tulentsev's answer in this thread.
def to_pig_latin(sentence)
sentence.gsub('.','').split(' ').collect do |word|
translate word
end.compact.join(' ')
end
def translate(word)
if word.length > 1
if word == 'and' || word == 'an' || word == 'in'
word
elsif capture = consonant_expression.match(word)
capture.post_match.to_s + capture.to_s + 'ay'
elsif vowel?(first_letter=word[0].downcase)
word + 'ay'
elsif vowel?(last_letter=word[-1].downcase)
move_last_letter(word) + 'ay'
end
else
word
end
end
# Move last letter to beginning of word
def move_last_letter(word)
word[-1] + word[0..-2]
end
private
def consonant_expression
# at the beginning of a String
# capture anything not a vowel (consonants)
# capture 1, 2 or 3 occurences
# ignore case and whitespace
/^ [^aeiou] {1,3}/ix
end
def vowel?(letter)
vowels.include?(letter)
end
def vowels
%w[a e i o u]
end
Also just for the heck of it I'll include my dump from a pry session so you all can see how to use MatchData. MINSWAN. It's stuff like this that makes ruby great.
pry > def consonant_expression
pry * /^ [^aeiou] {1,3}/ix
pry * end
=> :consonant_expression
pry > consonant_expression.match('Stream')
=> #<MatchData "Str">
pry > capture = _
=> #<MatchData "Str">
pry > ls capture
MatchData#methods:
== begin end hash length offset pre_match regexp string to_s
[] captures eql? inspect names post_match pretty_print size to_a values_at
pry >
pry > capture.post_match
=> "eam"
pry > capture
=> #<MatchData "Str">
pry > capture.to_s
=> "Str"
pry > capture.post_match.to_s
=> "eam"
pry > capture.post_match.to_s + capture.to_s + 'ay'
=> "eamStray"
pry >
If I understood your question correctly, you can just directly check if a character is a vowel or consonant and then use array ranges to get the part of the string you want.
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = ('a'..'z').to_a - vowels
return str + "ay" if vowels.include?(str[0])
if consonants.include?(str[0])
return str[2..-1] + str[0..1] + "ay" if consonants.include?(str[1])
return str[1..-1] + str[0] + "ay"
end
str
Here's a solution that handles the "qu" phoneme as well as other irregular characters. Had a little trouble putting the individual words back into a string with the proper spacing. Would appreciate any feedback!
def translate(str)
vowels = ["a", "e", "i", "o", "u"]
new_word = ""
str.split.each do |word|
vowel_idx = 0
if vowels.include? word[0]
vowel_idx = 0
elsif word.include? "qu"
until word[vowel_idx-2]+word[vowel_idx-1] == "qu"
vowel_idx += 1
end
else
until vowels.include? word[vowel_idx]
vowel_idx += 1
end
end
idx_right = vowel_idx
while idx_right < word.length
new_word += word[idx_right]
idx_right += 1
end
idx_left = 0
while idx_left < vowel_idx
new_word += word[idx_left]
idx_left += 1
end
new_word += "ay "
end
new_word.chomp(" ")
end
I done gone did one too
def translate(string)
vowels = %w{a e i o u}
phrase = string.split(" ")
phrase.map! do |word|
letters = word.split("")
find_vowel = letters.index do |letter|
vowels.include?(letter)
end
#turn "square" into "aresquay"
if letters[find_vowel] == "u"
find_vowel += 1
end
letters.rotate!(find_vowel)
letters.push("ay")
letters.join
end
return phrase.join(" ")
end
def piglatinize(word)
vowels = %w{a e i o u}
word.each_char do |chr|
index = word.index(chr)
if index != 0 && vowels.include?(chr.downcase)
consonants = word.slice!(0..index-1)
return word + consonants + "ay"
elsif index == 0 && vowels.include?(chr.downcase)
return word + "ay"
end
end
end
def to_pig_latin(sentence)
sentence.split(" ").collect { |word| piglatinize(word) }.join(" ")
end
This seems to handle all that I've thrown at it including the 'qu' phoneme rule...
def translate str
letters = ('a'..'z').to_a
vowels = %w[a e i o u]
consonants = letters - vowels
str2 = str.gsub(/\w+/) do|word|
if vowels.include?(word.downcase[0])
word+'ay'
elsif (word.include? 'qu')
idx = word.index(/[aeio]/)
word = word[idx, word.length-idx] + word[0,idx]+ 'ay'
else
idx = word.index(/[aeiou]/)
word = word[idx, word.length-idx] + word[0,idx]+'ay'
end
end
end
I'm grabbing the words with the 'qu' phoneme and then checking all the other vowels [excluding u].
Then I split the word by the index of the first vowel (or vowel without 'u' for the 'qu' cases) and dropping the word part before that index to the back of the word. And adding 'ay' ftw.
Many of the examples here are fairly long. Here's some relatively short code I came up with. It handles all cases including the "qu" problem! Feedback always appreciated (I'm pretty new to coding).
$vowels = "aeiou"
#First, I define a method that handle's a word starting with a consonant
def consonant(s)
n = 0
while n < s.length
if $vowels.include?(s[n]) && s[n-1..n] != "qu"
return "#{s[n..-1]}#{s[0..n-1]}ay"
else
n += 1
end
end
end
#Then, I write the main translate method that decides how to approach the word.
def translate(s)
s.split.map{ |s| $vowels.include?(s[0]) ? "#{s}ay" : consonant(s) }.join(" ")
end