How to extract values from an array

70 views Asked by At

How can I extract a particular number from the below array values between two underscores

names = [ "create_sales_3920_7873","create_sales_49204_7873","create_sales_392_7873"]

How to get output result as 3920, 49204, 392 from the above array

Any help is appreciable

2

There are 2 answers

0
caroline On BEST ANSWER

If the actual names array is quite long I'm sure there's a better way to do this, but looping over the array and using split will get the job done for the example you've posted:

names = [ "create_sales_3920_7873","create_sales_49204_7873","create_sales_392_7873"]


# initialize empty results array
output = []

# iterate over each string in array
names.each do |name|
  # use split to grab substring and add to results array
 output << name.split(/create_sales_/).last.split(/_/).first
end

#confirm result => ["3920", "49204", "392"]
puts output
2
Cary Swoveland On
names = [
  "create_sales_3920_7873",
  "create_sales_49204_7873",
  "create_sales_392_7873"
]
names.map { |s| s[/(?<=_)\d+(?=_)/] }
  #=> ["3920", "49204", "392"]

See String#[].

(?<=_) is a positive lookbehind that asserts that the match is immediately preceded by an underscore.

\d+ matches one or more digits, as many as possible.

(?=_)/ is a positive lookahead that asserts that the match is immediately followed by an underscore.

The regular expression therefore matches the first sequence of digits in the string that is preceded and followed by an underscore.


In a comment @3limin4t0r suggested

names.map { |s| s[/_(\d+)_/, 1] }

as an alternative.

We see that for the same strings s[/(?<=_)\d+(?=_)/] requires 936 steps and takes 3.2ms to execute, whereas [/_(\d+)_/, 1] takes only 324 steps and 0.3ms. That seems pretty clear-cut.