Praveenkumar
Praveenkumar

Reputation: 981

How can i get the value from array without using regex in ruby?

From the array of string I need to get string which starts with age- followed by maximum of 2 digit number and optional '+' sign.

Ex: age-1, age-22, age55, age-1+, age-15+

Following is my array:

arr = ["vintage-colllections","age-5"]
         or
arr = ["vintage-colllections","age-51+"]

I will extract age "age-5" or "age-51+" from the array.

I tried following things:

arr.find {|e| e.include?"age-"}

Works well for other scenarios but in above the 1st element of array also includes (vint)age- failing there.

arr.find { |e| /age-\d*\+?/ =~ e} 

Works fine but I am trying to avoid regex.

Is there any other better approach ?. Any suggestions are welcome.

Upvotes: 0

Views: 71

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

I must grit my teeth to not use a regex, but here goes. I assume the question is as described in a comment I left on the question.

def find_str(arr)
  arr.map { |str| str_match(str) }.compact
end

def str_match(str)
  return nil unless str[0,4] == "age-"
  last = str[-1] == '+' ? -2 : -1
  Integer(str[4..last]) rescue return nil
  str
end

find_str ["cat", "age-5"]     #=> ["age-5"] 
find_str ["cat", "age-51+"]   #=> ["age-51+"] 
find_str ["cat", "age-5t1+"]  #=> [] 
find_str ["cat", "xage-51+"]  #=> [] 

Upvotes: 2

Inpego
Inpego

Reputation: 2667

Use start_with?:

arr.find { |e| e.start_with?("age-") }

Upvotes: 5

Related Questions