arrays - 返回字符串中使用的元音数组
问题描述
我正在努力应对红宝石挑战,任务是
编写一个方法,该方法将接受一个字符串并返回该字符串中使用的元音数组。
示例: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
解决方案
出于学术目的,这是另一种方法:
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
文档中的示例。
推荐阅读
- scala - 如何在scala中使用withColumn函数将可变列表添加为数据框的列
- java - 如何在java中使用反射将对象传递给方法
- intellij-idea - 类似于 IntelliJ 如何以蓝色显示未提交的更改,是否有类似的方式来显示最后一次提交的更改?
- ios - Swift Combine 不会通过接收器更新值
- python - 如何监控多个进程并在一个退出时启动新的进程?
- c# - Excel 数据阅读器:变量列表使用 Clear() 方法丢失列表内容
- javascript - 如何获取对象内部的值?
- javascript - 奇怪的警告:已声明但它的值从未被读取
- javascript - Google App脚本根据该单元格的字体颜色清除单元格值
- xcode - Xcode 10.3 不适用于 MacOS Big Sur 11.0.1(非测试版)