Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract values from an array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help is appreciable

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading