Ruby code for deleting the vowels in a string - ruby

I'm trying to write code in Ruby that removes all the vowels from a string:
def remvowel(string)
i = 0
dv_string = []
while i < string.length
if (string[i] != "a" || string[i] != "e" || string[i] != "i" || string[i] != "o" || string[i] != "u")
dv_string.push(i)
i += 1
end
i += 1
end
return dv_string.join
end
But it's not coming out right. When I run remvowel("duck"), it returns "02", as in the index positions of "dc". I'm missing something, but I don't know what.

You could just:
string.gsub(/[aeiou]/, '')
Or even better:
string.tr('aeiou', '')
And the best tool for deleting characters in a string is...
string.delete('aeiou')

That's because you're pushing i instead of string[i].
dv_string.push(i)
This is what you want:
dv_string.push(string[i])
However, that's a rather verbose and roundabout way of accomplishing the task. A somewhat more idiomatic Ruby approach would look like any of the ones ndn posted:
def remvowel(string)
string.gsub /[aeiou]/, ''
end
or
def remvowel(string)
string.tr 'aeiou',''
end
or
def remvowel(string)
string.delete 'aeiou'
end

You've got it almost right:
def remvowel(string)
i = 0
dv_string = []
while i < string.length
if (string[i] != "a" || string[i] != "e" || string[i] != "i" || string[i] != "o" || string[i] != "u")
# Push the letter, not i
dv_string.push(string[i])
# Don't increment i here
end
i += 1
end
return dv_string.join
end
Your algorithm increments i twice if you encounter a consonant, so you are skipping every second letter.

Here is one more way this can be done:
s = "Hello, how are you you?"
vowels = "aeiou"
puts (s.chars - vowels.chars).join
#=> Hll, hw r y y?

Thank you everybody for your contributions. Thanks to you all (and especially you, Cary Swoveland), I not only know better ways to do this in the future, but even found an answer for my "scenic route" way of doing it!
def remvowel(string)
i = 0
dv_string = []
while i < string.length
dv_string.push(string[i])
if (string[i] == "a" || string[i] == "e" || string[i] == "i" || string[i] == "o" || string[i] == "u")
dv_string.delete(string[i])
end
i += 1
end
return dv_string.join
end
Granted, I'm gonna be doing the more sensible way from the responses here from now on, but mission accomplished!

Related

Ruby doesn't recognize `downcase` or `split` as defined methods? [duplicate]

This question already has answers here:
Why word 'translate' is messing irb?
(2 answers)
Closed 6 years ago.
The issue is with the following code:
#write your code here
def translate phrase
phrase = phrase.downcase.split(/ /)
phrase.collect! do |word|
word = word.split(//)
switched = false
while switched == false
word.each_index do |letter|
if word[letter] == ("a" || "e" || "i" || "o" || "u")
switched = true
word = (word[letter..-1] + word[0..(letter-1)]).join + "ay"
end
end
end
end
return phrase.join(" ")
end
puts translate("chocolate cream")
#Should return "ocolatechay eamcray"
When I run this, Ruby just returns a blank line. So, to troubleshoot the issue, I loaded the definition into a repl. The repl returned the following error:
NoMethodError: undefined method `downcase' for #<RubyVM::InstructionSequence:0x000000016e8f88>
from /home/adc/odin-project/web-development-101/21-ruby-tdd/ruby_tdd_project/learn_ruby/04_pig_latin/pig_latin.rb:3:in `translate'
from /home/adc/.rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'
If I remove downcase from my code, I get the same error message, only this time with split.
What's the problem here? (I'm pretty confident that downcase and split are not the problem.)
If returns a blank string because you don't return anything inside the collect! block. Return word and it will work :
def translate phrase
phrase = phrase.downcase.split(/ /)
phrase.collect! do |word|
word = word.split(//)
switched = false
while switched == false
word.each_index do |letter|
if word[letter] == ("a" || "e" || "i" || "o" || "u")
switched = true
word = (word[letter..-1] + word[0..(letter-1)]).join + "ay"
end
end
end
word
end
return phrase.join(" ")
end
puts translate("chocolate cream")
#=> atechocolay amcreay
It doesn't look like it's returning exactly what you expected, but it's still better than a blank string.
As for your weird error message in the console, it seems to be specific to the REPL (possibly because of the method name translate).
Update 1 (how I would write this code)
def translate phrase
phrase = phrase.downcase.split(/ /)
phrase.collect! do |word|
word = word.split(//)
word.each_index do |letter|
if ["a", "e", "i", "o", "u"].include?(word[letter])
if letter == 0
word = word[letter..-1].join + "ay"
else
word = (word[letter..-1] + word[0..(letter-1)]).join + "ay"
end
break
end
end
word
end
return phrase.join(" ")
end
puts translate("chocolate cream")
Update 2 (if I make some minor changes to your code to make it useful)
def translate phrase
phrase = phrase.downcase.split(/ /)
phrase.collect! do |word|
word = word.split(//)
switched = false
while switched == false
word.each_index do |letter|
if ["a", "e", "i", "o", "u"].include?(word[letter])
switched = true
if letter == 0
word = word[letter..-1].join + "ay"
else
word = (word[letter..-1] + word[0..(letter-1)]).join + "ay"
end
break
end
end
end
word
end
return phrase.join(" ")
end
puts translate("chocolate cream")
Explanation
"o"==("a" || "e" || "i" || "o" || "u")
and
"o"== "a" || "o" == "e" || "o" == "i" || "o" == "o" || "o" == "u"
statements are not the same. First one is false
(because ("a" || "e" || "i" || "o" || "u")=="a" and "o"!="a"), since the second one is true.
You need inner if statement
if letter == 0
word = word[letter..-1].join + "ay"
else
word = (word[letter..-1] + word[0..(letter-1)]).join + "ay"
end
because when word starts with any mentioned vowels then
word[letter..-1] + word[0..(letter-1)]
statement will return the whole word twice, cause letter will equal to 0.
And lastly you need to return word object after the while loop.

ruby returning true if a string consists an "a" and then a "z"

I need help on Writing a method that takes a string in and returns true if the letter "z" appears within three letters after an "a". You may assume that the string contains only lowercase letters. here's what I have:
def nearby_az(string)
string.downcase!
i = 0
while i < string.length
if (string[i] == "a" && string[i] == "z")
true
else
false
end
end
end
puts('nearby_az("baz") == true: ' + (nearby_az('baz') == true).to_s)
puts('nearby_az("abz") == true: ' + (nearby_az('abz') == true).to_s)
puts('nearby_az("abcz") == true: ' + (nearby_az('abcz') == true).to_s)
puts('nearby_az("a") == false: ' + (nearby_az('a') == false).to_s)
puts('nearby_az("z") == false: ' + (nearby_az('z') == false).to_s)
puts('nearby_az("za") == false: ' + (nearby_az('za') == false).to_s)
A regular expression would be the best for this. Try
def nearby_az(string)
(string =~ /a.{0,2}z/) != nil
end
EDIT:
as per the "if statement required requirement" :)
def nearby_az(string)
if (string =~ /a.{0,2}z/) != nil
return true
end
return false
end
The way this code works is it searches the input string for an "a". After that, the period indicates that you can have any character. After that you have {0,2} which is a modifier of the period indicating you can have 0 to 2 of any character. After this you must have a "z", and this fulfills your must have a z within 3 characters of an "a".
I've saved this regex to regex101 here so you can try various inputs as well as change the regular expression around to understand it better.
To fix you code you need to:
increment i at the end of the loop.
search the z letter within the 3 next letters
return true when condition is met
return false when getting out of the loop
Here is what it should look like:
def nearby_az(string)
string.downcase!
i = 0
while i < string.length do
return true if string[i] == "a" && string[i+1,3].include?(?z)
i+=1
end
return false
end

Why can't I find `"az"` in a string with this function?

I want to know if "a" and "z" are together in a string after I have found "a". I'd like to understand why this does not work:
def nearby_az(string)
i = 0
while i < string.length
if string[i] == "a" && string[i+1] == "z"
return true
else
return false
end
i += 1
end
end
I realize there is a simple way to implement this. I am not looking for another solution.
This code will only find "az" if it's at the very beginning. Otherwise it will return false. Postpone return false until you walked the whole string.
def nearby_az(string)
i = 0
while i < string.length -1
return true if string[i] == "a" && string[i+1] == "z"
i += 1
end
# we can only reach this line if the loop above does not return.
# if it doesn't, then the substring we seek is not in the input.
return false
end
nearby_az('baz') # => true
#Segio Tulentsev' s answer explains why yours is broken.
Here's the short implementation if you're interested
def nearby_az(str)
!! str =~ /a(?=z)/i
end

What's wrong with this Ruby program that counts vowels?

When I test this program on strings the output is 0. I think my logic is sound and it's just a minor syntax thing. Anyone see the problem?
def VowelCount(string)
string.downcase
i = 0
vowels = 0
until i == string.length-1
if (string[i] == "a" || string[i] == "o" || string[i] == "e" || string[i] == "i" || string[i] == "u")
vowels += 1
end
i += 1
end
return vowels
end
You can use String#count:
str = "It was the best of times, it was the worst of times,..."
str.downcase.count('aeiou') #=> 14
The following line
until i == string.length-1
should be:
until i == string.length
Otherwise, the last character is not checked.
BTW, by convension, method name starts with lower case, and combined with underscore. Here's an alternative solution using regular expression.
def vowel_count(string)
string.scan(/[aeiou]/i).length
end
update
As JesseSielaff pointed, String#downcase does not change the string in place. You need to assign the return value of the method back or use String.downcase!

How do I count vowels?

I've seen the solution and it more or less matches
Write a method that takes a string and returns the number of vowels
in the string. You may assume that all the letters are lower cased. You can treat "y" as a consonant.
Difficulty: easy.
def count_vowels(string)
vowel = 0
i = 0
while i < string.length
if (string[i]=="a" || string[i]=="e" || string[i]=="i" || string[i]=="o"|| string[i]=="u")
vowel +=1
end
i +=1
return vowel
end
puts("count_vowels(\"abcd\") == 1: #{count_vowels("abcd") == 1}")
puts("count_vowels(\"color\") == 2: #{count_vowels("color") == 2}")
puts("count_vowels(\"colour\") == 3: #{count_vowels("colour") == 3}")
puts("count_vowels(\"cecilia\") == 4: #{count_vowels("cecilia") == 4}")
def count_vowels(str)
str.scan(/[aeoui]/).count
end
/[aeoui]/ is a regular expression that basically means "Any of these characters: a, e, o, u, i". The String#scan method returns all matches of a regular expression in the string.
def count_vowels(str)
str.count("aeoui")
end
Your function is fine you are just missing a keyword end to close of your while loop
def count_vowels(string)
vowel = 0
i = 0
while i < string.length
if (string[i]=="a" || string[i]=="e" || string[i]=="i" || string[i]=="o"|| string[i]=="u")
vowel +=1
end
i +=1
end
return vowel
end
puts("count_vowels(\"abcd\") == 1: #{count_vowels("abcd") == 1}")
puts("count_vowels(\"color\") == 2: #{count_vowels("color") == 2}")
puts("count_vowels(\"colour\") == 3: #{count_vowels("colour") == 3}")
puts("count_vowels(\"cecilia\") == 4: #{count_vowels("cecilia") == 4}")
#=> count_vowels("abcd") == 1: true
#=> count_vowels("color") == 2: true
#=> count_vowels("colour") == 3: true
#=> count_vowels("cecilia") == 4: true
I think using HashTable data structure would be good way to go for this particular problem. Especially if you're required to output number of every single vowel separately.
Here is the code I'd use:
def vowels(string)
found_vowels = Hash.new(0)
string.split("").each do |char|
case char.downcase
when 'a'
found_vowels['a']+=1
when 'e'
found_vowels['e']+=1
when 'i'
found_vowels['i']+=1
when 'o'
found_vowels['o']+=1
when 'u'
found_vowels['u']+=1
end
end
found_vowels
end
p vowels("aeiou")
Or even this (elegant but not necessarily performant):
def elegant_vowels(string)
found_vowels = Hash.new(0)
string.split("").each do |char|
case char.downcase
when ->(n) { ['a','e','i','o','u'].include?(n) }
found_vowels[char]+=1
end
end
found_vowels
end
p elegant_vowels("aeiou")
which would output:
{"a"=>1, "e"=>1, "i"=>1, "o"=>1, "u"=>1}
So you don't have to turn the string into an array and worry about case sensitivity:
def getVowelCount(string)
string.downcase.count 'aeiou'
end

Resources