Remove vowels from a string

Hi all.

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

puts "Enter a string:: "
string=gets.chomp.to_s

s=remove_vowels(string)

puts “Original string: #{string}”
puts “String without vowels >> #{s}”
##############################################################

Thanks.

Try str.gsub(/[aeiou]/i, ‘’)

Hi,

Or a bit more straightforward:

str.delete ‘aeiouAEIOU’

Joao S. wrote in post #1067214:

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.

Tony is right that it’s a better solution, but let’s try figuring out
why yours doesn’t work.

2012/7/3 Joao S. [email protected]:

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.