1

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 if starts_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?

6
  • You know about start_with? already. So, where's your code? Commented Nov 1, 2013 at 18:14
  • Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. Commented Nov 1, 2013 at 18:14
  • I know start_with? from here ruby-doc.org/core-2.0.0/String.html#method-i-start_with-3F Commented Nov 1, 2013 at 18:18
  • 1
    I mean, try to solve this yourself. If you were blocked in your previous question, now you should be unblocked (you should have the basic understanding about how those solutions work). We won't always be here to write code for you. :) Commented Nov 1, 2013 at 18:20
  • 1
    Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. Commented Mar 1, 2014 at 22:51

2 Answers 2

3

Another way:

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"] 
Sign up to request clarification or add additional context in comments.

Comments

1

The concept is the same that of your previous question.

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

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

def subarray(array, range)
  from = range.first
  to = range.last
  idx_from = array.index{ |e| e.start_with?(from) }
  idx_to = array.index{ |e| e.start_with?(to) }
  array[idx_from..idx_to]
end

p subarray(array, range_1)
#=> ["CCC", "DDD"]

p subarray(array, range_2)
#=> ["BBB", "CCC", "DDD", "EEE"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.