I’m trying to make a program that removes all the vowels in a string
entered, but no I’m doing wrong. This is the code I am doing:
##########################################################
def remove_vowels(string)
vowels = %w{a e i o u A E I O U}
str = “”
for i in 0…string.length
if not string[i]==vowels[i] then
str[i]=string[i]
end
end
return str
end
I’m trying to make a program that removes all the vowels in a string
entered, but no I’m doing wrong. This is the code I am doing:
Ruby is not Java or C! You should get rid of this lowlevel programming
style and take a more highlevel approach.
It’s very rare in Ruby that you actually have to build a string
character by character in a loop. There’s almost always a more
intelligent way to do this (like String#delete or String#gsub in this
case).
Apart from that, you shouldn’t use the “for” loop. It’s just ugly and
has the disadvantage of not creating a new scope (i. e. the loop
variable is accessible from the outside). Use an iterator like
String#each_char.
for i in 0…string.length
if not string[i]==vowels[i] then
str[i]=string[i]
end
end
There are two errors here. First, you’re not checking all the vowels,
only one of them for every letter of string (or none when you reach
the end of array). You should use Array#include? here:
The second is that the string “str” is empty, and thus you can’t
assign letters to any of its indices. You could use String#<< (or
String#concat):
– Matma R.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.