Hemant Bhargava
Hemant Bhargava

Reputation: 3585

regex match and split in ruby

I have an big string of this format:

FA dir_name1 file_name1
FA dir_name1 file_name2
FA dir_name2 file_name1
FA dir_name2 file_name2
....

I was thinking if we can write an regex expression while doing split which returns me an array consisting of this:

["dir_name1/file_name1", "dir_name1/file_name2", "dir_name2/file_name1", "dir_name2/file_name2"]

I have tried splitting the big string first and then do regex. It works but can't we do it using easier way?

Any other way to do this?

Upvotes: 2

Views: 152

Answers (3)

iGian
iGian

Reputation: 11183

I just wanted try to use Ruby 2.6 Object#then:

input.lines.map { |s| s.split.then { |e| e.last(2).join('/') } }

#=> ["dir_name1/file_name1", "dir_name1/file_name2", "dir_name2/file_name1", "dir_name2/file_name2"]

Upvotes: 0

Amadan
Amadan

Reputation: 198314

This should work even in an antediluvian Ruby:

input.lines.map { |line| line.strip[2..-1].sub(' ', '/') }

You have to do it in two steps, because any function that could split (split, lines, scan) cannot give you the slashes.

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

As you wish to get an array out of string, some split is required.

input.scan(/(?<=^FA ).*$/).
      map { |e| e.split.join('/') }
#⇒ [
#   [0] "dir_name1/file_name1",
#   [1] "dir_name1/file_name2",
#   [2] "dir_name2/file_name1",
#   [3] "dir_name2/file_name2"
#  ]

It scans the input using positive lookbehind to get the desired result out of the box, splits it by space and joins with a slash.


Another way round would be to just split several times:

input.
  split($/).
  map { |line| line.split[1..-1].join('/') }

Upvotes: 2

Related Questions