0

我最初写了一个方法来获取一个单词并找出它的元音是否按字母顺序排列。我使用下面的代码做到了:

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

但是,我决定尝试使用 all? 方法。我尝试使用以下代码执行此操作:

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")

任何人都有任何想法为什么它不起作用?我原以为这会奏效。另外,如果有人有更好的解决方案,请随时发布。谢谢!

例子是:

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
4

2 回答 2

2

这是我的做法:

#!/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")

输出是:

true
false

all?在您的原始示例中,您使用数组值(字符串)作为数组索引,当方法触发时它应该是整数。

于 2013-05-28T18:31:32.723 回答
2
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仅包含“o”,并且在vowels_in_word.all? {|x| vowels_in_word[x]<= vowels_in_word[x+1]}表达式内部vowels_in_word[x]表示vowels_in_word["o"],这反过来又会引发错误,因为索引永远不会是string

于 2013-05-28T18:31:54.997 回答