-1

Why does this happen:

filename
=> "/Users/user/Desktop/work/arthouse/digitization/in-process/cat.jpg"
[4] pry(DigitizedView)> filename.gsub(/.*\//,'')
=> "cat.jpg"

What is the regex in the first argument of gsub? I know the .* is any number of any characters... but what is the backslash? Why does it delete everything except the cat.jpg part?

Also,

"cat.jpg".scan(/(\w+)-(\d+)([a-z]?)/)
=> []

What is that code doing?

Jwan622
  • 11,015
  • 21
  • 88
  • 181

2 Answers2

0

let us examine what this first argument for the gsub method, /.*\// means.

the first and last slashes /.../ denotes that we are dealing with a regex here, not string.

There are two parts to this regex. .* and \/.

.* says that grep any characters, including empty character.

\/ says that grep a string with a slash, /.

This regex would catch,

['/', 'Users/', 'user/', 'Desktop/', 'work/', 'arthouse/', 'digitization/', 'in-process/']

All these strings are now replaced with ''.

Except cat.jpg which doesn't have the slash at the end.

Hope that explanation helps.

  • edit

In the second part, /(\w+)-(\d+)([a-z]?)/

(\w+): grep a group of word characters (includes numbers) -: grep for a dash (\d+): grep a group of numeric digits ([a-z]?): grep for nil char or a single char.

cat.jpg doesn't fit into this regex in many ways. No dash, . in the string. etc.

Therefore, scan will return an empty array.

Jason Kim
  • 18,102
  • 13
  • 66
  • 105
0

The Regexp /.*\// matches zero or more characters terminated by a forward slash. The String#gsub method replaces all substrings matching the pattern with the replacement value, in this case ''.

So in this case, the pattern matches the following substrings: '/', 'Users/', 'user/', 'Desktop/', 'work/', 'arthouse/', 'digitization/', and 'in-process/'. It replaces each of these with a blank string. It does not match the remaining substring, cat.jpg, because that substring doesn't terminate with a '/'. So 'cat.jpg' is all that remains.

hoffm
  • 2,386
  • 23
  • 36