JaTo
JaTo

Reputation: 2832

Why is my all? function not working? What's wrong with my syntax?

I originally wrote a method to take a word and find out if its vowels were in alphabetical order. I did it by using the code below:

def ordered_vowel_word?(word)
  vowels = ["a", "e", "i", "o", "u"]

  letters_arr = word.split("")
  vowels_arr = letters_arr.select { |l| vowels.include?(l) }

  (0...(vowels_arr.length - 1)).all? do |i|
    vowels_arr[i] <= vowels_arr[i + 1]
  end
end

However, I decided to try to change it by using an all? method. I tried to do so with the following code:

def ordered_vowel_word?(word)
  vowels = ["a","e", "i", "o", "u"]
  splitted_word = word.split("")
  vowels_in_word = []
  vowels_in_word = splitted_word.select {|word| vowels.include?(word)}

  vowels_in_word.all? {|x| vowels_in_word[x]<= vowels_in_word[x+1]}


end


ordered_vowel_word?("word")

Anyone have any ideas why it isnt working? I would have expected this to work. Also, if anyone has a better solution please feel free to post. Thanks!

Examples are:

it "does not return a word that is not in order" do
  ordered_vowel_words("complicated").should == ""
end

it "handle double vowels" do
  ordered_vowel_words("afoot").should == "afoot"
end

it "handles a word with a single vowel" do
  ordered_vowel_words("ham").should == "ham"
end

it "handles a word with a single letter" do
  ordered_vowel_words("o").should == "o"
end

it "ignores the letter y" do
  ordered_vowel_words("tamely").should == "tamely"
end

Upvotes: 0

Views: 168

Answers (2)

squiguy
squiguy

Reputation: 33380

Here is how I would do it:

#!/usr/bin/ruby

def ordered?(word)
  vowels = %w(a e i o u)
  check = word.each_char.select { |x| vowels.include?(x) }
  # Another option thanks to @Michael Papile
  # check = word.scan(/[aeiou]/)
  puts check.sort == check
end

ordered?("afoot")
ordered?("outaorder")

Output is:

true
false

In your original example, you use the array values (String) as array indices which should be Integers when the all? method fires.

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118289

def ordered_vowel_word?(word)
    vowels = ["a","e", "i", "o", "u"]
    splitted_word = word.split("")
    vowels_in_word = []
    vowels_in_word = splitted_word.select {|word| vowels.include?(word)}
    p vowels_in_word #=> ["o"]
    vowels_in_word.all? {|x| vowels_in_word[x]<= vowels_in_word[x+1]}
end

p ordered_vowel_word?("word")
#=> `[]': no implicit conversion of String into Integer (TypeError)

vowels_in_word contains only 'o', and inside the vowels_in_word.all? {|x| vowels_in_word[x]<= vowels_in_word[x+1]} the expression vowels_in_word[x] means vowels_in_word["o"], which in-turn throws error as index can never be string.

Upvotes: 2

Related Questions