Return sub-array from defined range by substrings of defined array elements

来源:互联网 发布:开淘宝商城开店步骤 编辑:程序博客网 时间:2024/05/29 10:12

I have a sorted array of elements (unique and not consecutive):

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

I defined a range of elements:

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

The range of elements are just strings which refers to an array elements but only ifstarts_with? is true for these elements. Example:

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

The desired results for range_1 and range_2 would be like this:

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

How to implement this in Ruby?


Another way:

def git_em(array, range)  array.select {|e| range.any? {|r| e.start_with? r}}endarray= ["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"] 

0 0
原创粉丝点击