0

I have the following string:

expression_patterns_attributes_2_location_attributes_PTN_PATTERN

I need to extract only the number after 'expression_patterns_attributes_'

I did the following:

<%= string_a = "expression_patterns_attributes_2_location_attributes_PTN_PATTERN"
<% z_index1 = string_a.slice! "expression_patterns_attributes_" %>
<% z_index2 = string_a.slice! "_location_attributes_PTN_PATTERN"     %>
<%= string_a %> yields '2'

Is there a neater way of extracting the number from the string?

Thanks for your suggestion

2 Answers 2

2
s = 'expression_patterns_attributes_2_location_attributes_PTN_PATTERN'
s[/\d+/] # => "2"
Sign up to request clarification or add additional context in comments.

1 Comment

Yep this is actually a lot more robust!
1

If you're sure that string_a is always well formed :

string_a.split("_")[3]

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.