gpt4 book ai didi

ruby - 通过已定义数组元素的子字符串从已定义范围返回子数组

转载 作者:太空宇宙 更新时间:2023-11-03 17:53:20 25 4
gpt4 key购买 nike

我有一个排序的元素数组(唯一且不连续):

array= ["AAA", "BBB", "CCC", "DDD", "EEE"]

我定义了一系列元素:

range_1 = ("CC" .. "DD")
range_2 = ("B" .. "E")

元素的范围只是引用 array 元素的字符串,但前提是这些元素的 starts_with?true。示例:

"C", "CC" and "CCC" in range - fits to "CCC" in array
"D", "DD" and "DDD" in range - fits to "DDD" in array

range_1range_2 的预期结果如下:

result_1 = ["CCC", "DDD"]
result_2 = ["BBB", "CCC", "DDD", "EEE"]

如何在 Ruby 中实现它?

最佳答案

另一种方式:

def git_em(array, range)
array.select {|e| range.any? {|r| e.start_with? r}}
end

array= ["AAA", "BBB", "CCC", "DDD", "EEE"]
range_1 = ("CC" .. "DD")
range_2 = ("B" .. "E")

git_em(array,range_1) # => ["CCC", "DDD"]
git_em(array,range_2) # => ["BBB", "CCC", "DDD", "EEE"]

关于ruby - 通过已定义数组元素的子字符串从已定义范围返回子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19732759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com