Domanda

I don't know much about Ruby, but I have this line of code that I would like to know what it exactly does:

newline.gsub!(/\s+(های)\s+/,'‌\1 ')

I appreciate any help on this.

È stato utile?

Soluzione

The regular expression matches if a string contains the persian phrase with one or more whitespace characters around it (both at the front and back).

Then it replaces it with the string \1. The \1 refers to the first matched element. So, it removes all the whitespace around the string and adds one space after the element.

Example

I am taking the value test instead of the Parsi phrase, because unicode wasn't working out.

newline = "    test   "
=> "    test   "
newline.gsub!(/\s+(test)\s+/,'\1 ') 
=> "test "

Altri suggerimenti

The documentation says:

gsub!(pattern, replacement) → str or nil

So your expression would return the substituted string if it matched the pattern, else return nil. (Essentially remove all the whitespaces before the farsi string and replace the ones following it with a single whitespace.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top