1.count 方法可以加入條件:count 不只能做 array.count 計算個數,還可以加入篩選條件,如 string.count('aeoiu'),計算 string 中符合「a」「e」「i」「o」「u」的個數有幾個
# 計算有幾個母音字母(a, e, i, o, u)
def vowel_count(string)
# 實作內容
end
RSpec.describe do
it "計算有幾個母音字母" do
expect(vowel_count("abracadabra")).to be 5
expect(vowel_count("5xruby")).to be 1
expect(vowel_count("iloveyou")).to be 5
end
end
def vowel_count(string)
string.chars.select { |n| n == 'a' || n == 'e' || n == 'i' || n == 'o' || n == 'u'}.count
end
def vowel_count(string)
string.count('aeiou')
end
(可…可惡,果然有超簡單的方法)