Return 字符串中使用的元音数组
Return an array of vowels used within a string
我正在努力应对 ruby 挑战,任务是
编写一个方法,它将接受一个字符串和
return 该字符串中使用的元音数组。
示例:
count_vowels("The quick brown fox") 应该 return ["e","u","i","o","o"]
count_vowels("Hello World") 应该 return ["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
下面的代码片段应该能帮到你
已编辑:-
def count_vowels(word)
word.downcase.chars.select{|c| %[a,e,i,o,u].include?(c)}
end
出于学术目的,这是另一种方法:
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
文档中的示例。
您可以通过将 String.scan
与正则表达式一起使用来避免首先将字符串拆分为字符数组。
string = "The quick brown fox"
string.scan(/(a|e|i|o|u)/i).flatten
#=> ["e", "u", "i", "o", "o"]
string = "Hello World"
string.scan(/(a|e|i|o|u)/i).flatten
#=> ["e", "o", "o"]
末尾的 i
使正则表达式不区分大小写。
这可能取决于字符串的大小,如果构建正则表达式并一次性扫描字符串或先将字符串拆分为数组然后遍历所有字符并将它们与另一个数组进行比较会更快.
我正在努力应对 ruby 挑战,任务是
编写一个方法,它将接受一个字符串和 return 该字符串中使用的元音数组。
示例: count_vowels("The quick brown fox") 应该 return ["e","u","i","o","o"]
count_vowels("Hello World") 应该 return ["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
下面的代码片段应该能帮到你
已编辑:-
def count_vowels(word)
word.downcase.chars.select{|c| %[a,e,i,o,u].include?(c)}
end
出于学术目的,这是另一种方法:
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
文档中的示例。
您可以通过将 String.scan
与正则表达式一起使用来避免首先将字符串拆分为字符数组。
string = "The quick brown fox"
string.scan(/(a|e|i|o|u)/i).flatten
#=> ["e", "u", "i", "o", "o"]
string = "Hello World"
string.scan(/(a|e|i|o|u)/i).flatten
#=> ["e", "o", "o"]
末尾的 i
使正则表达式不区分大小写。
这可能取决于字符串的大小,如果构建正则表达式并一次性扫描字符串或先将字符串拆分为数组然后遍历所有字符并将它们与另一个数组进行比较会更快.