我正在尝试编写接受字符串数组并返回小于 6 或以“y”结尾的字符串的代码,但不能同时返回两者。
问题不希望返回新数组。如果我要返回一个符合条件的新字符串数组,我编写的代码会起作用,但是如果我尝试只返回字符串而不是数组,则它不起作用。
# frozen_string_literal: true
def select_long_words(words)
str = []
i = 0
while i < words.length
word = words[i]
if (word.length < 6 || word[-1] == 'y') && !(word.length < 6 && word[-1] == 'y')
str << word
end
i += 1
end
str
end
print select_long_words(%w[whatever are butterfly wit foreward funny])
puts
print select_long_words(%w[keepers cody])
这是返回符合条件的新字符串数组的代码。
你的问题有点不清楚,但我会尽力回答。
要选择少于 6 个字符或(仅)以“y”结尾的单词s,您可以使用此功能:
def select_long_words(words)
words.select do |word|
is_less_than_6 = word.size < 6
ends_with_y = word.end_with?('y')
# Select only if one of the two condition is respected, not both or none
next is_less_than_6 ^ ends_with_y
end
end
在这个函数中,我使用了select
Array 中的函数,它代表“选择与给定条件相对应的每个元素”,并将条件设置为“少于 6 个字符或以 'y' 结尾,但不是两者”,使用^
which mean xor for booleans .
如果你只想要一个词,你可以这样调用你的函数:
select_long_words(["whatever", "are", "butterfly", "wit", "foreward", "funny"]).first
如果没有对应关系,或者对应的第一个单词,它将返回 nil。可以在方法中替换select
withfind
直接得到第一个结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句