我试图找到它由几句话包含数组中的第一个字符。
我把所有的话,但我不知道如何检查的所有????第一个字符!!!!!
def strange_words(words)
newarray = []
i = 0
while i < words.length
letters = words[i]
if ???? #problem is here
end
i += 1
end
return newarray
end
puts strange_words(["eating", "period", "value", "earth"])
例如,在值的第一个字符是“V”,我想这一点。谢谢
Array#select返回包含所述给定块返回一个真值进制中的所有元素的新数组。
def strange_words(array, started_character)
array.select{|m| m.start_with?(started_character)}
end
输出:
strange_words(["eating", "period", "value", "earth"], 'ea')
#=> ["eating", "earth"]
干杯
我假定具有所需性质的所有字是在阵列中,而不是仅第一个这样的字将被返回。现在的问题是不太清楚的是,反映在不同的答案。
def strange_words(words, begins_with)
words.grep /\A#{begins_with}/
end
words = ["eating", "period", "value", "earth", "vortex", "evenly"]
strange_words(words, "v")
#=> ["value", "vortex"]
strange_words(words, "ea")
#=> ["eating", "earth"]
strange_words(words, "z")
#=> []
见Enumerable#grep。正则表达式读取,“匹配其次是\A
值的字符串字符串(begins_with
)的开始。”
如果只有第一场比赛将返回一个选择是让grep
一个懒惰的枚举,以停止搜索第一个匹配后发现:
def strange_words(words, begins_with)
words.lazy.grep(/\A#{begins_with}/).first
end
strange_words(words, "v")
#=> "value"
Array#find正是这样做的。它返回匹配的块中的条件的第一元件:
你可以像这样的方法:
def first_word_starting_with(array, characters)
array.find { |el| el.start_with? characters }
end
arr = ["eating", "period", "value", "earth"]
first_word_starting_with(arr, "v")
# => "value"