首页 > 解决方案 > 返回字符串中使用的元音数组

问题描述

我正在努力应对红宝石挑战,任务是

编写一个方法,该方法将接受一个字符串并返回该字符串中使用的元音数组。

示例:count_vowels("The quick brown fox") 应该返回 ["e","u","i","o","o"]

count_vowels("Hello World") 应该返回 ["e","o","o"]

到目前为止,我已经尝试过使用块和其他数组方法,例如

def vowels(string)
 string_array = string.chars
  vowels = ["a", "e", "i", "o", "u"]
  p string_array & vowels

end

def vowels (string)
  # Your code here
  arr =(string).downcase.chars
    new =[]
  values = ["a","e","i","o","u"]
arr. { |words| values.include?(words.each) }
    end

标签: arraysrubyblock

解决方案


出于学术目的,这是另一种方法:

def vowels(str)
  # Delete all the non-vowel characters from the string and return the remaining characters
  str.downcase.tr('^aeiou', '').chars
end

vowels("The quick brown fox")
# => ["e", "u", "i", "o", "o"]
vowels("Hello World")
# => ["e", "o", "o"]

巧合的是,这基于String#tr文档中的示例。


推荐阅读