Warm tip: This article is reproduced from serverfault.com, please click

ruby not equal operator doesn't work but equal does

发布于 2020-11-28 19:27:30

I'm very puzzled with this simple method I have where I'm just trying to puts a character of an array if, when compared with the character of another array, it is different.

This works with the == operator but not with the !=

Maybe it has to do with the each loops but I can't see what the error is. Any ideas?

Thanks

def remove_vowels(s)
 nw_s = s.chars
 vowels = "aeiou".chars
 result = []
  nw_s.each do |char|
    vowels.each do |vowel|
      if char != vowel
        print char
      end
    end
  end
end

remove_vowels("apple")
Questioner
Peter muller
Viewed
0
Mateo977 2020-11-29 04:12:42

Nested each is no ruby way of doing this kind of task. You can write this

def remove_vowels(s)
  nw_s = s.chars
  vowels = "aeiou".chars
  result = nw_s.map {|k| k unless vowels.include?(k) }.compact
end

remove_vowels("apple")

One line of code instead seven