-1

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.

TJ1
  • 7,578
  • 19
  • 76
  • 119
  • 3
    Reading the documentation is always a really good starting point. It doesn't look like you expended much energy doing that. A very simple Google search for ["ruby gsub"](https://www.google.com/search?q=ruby+gsub) would have started you on your path to answering your question. That would have led you to looking up ["ruby regexp"](http://www.ruby-doc.org/core-2.1.0/Regexp.html). – the Tin Man Jan 23 '14 at 14:20

2 Answers2

1

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 "
Zero Fiber
  • 4,417
  • 2
  • 23
  • 34
1

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.)

devnull
  • 118,548
  • 33
  • 236
  • 227
  • Thanks for the answer. Since Farsi language is written right to left, did you mean: it remove all the whitespaces after the Farsi string and replace the ones before it with a single whitespace? – TJ1 Jan 23 '14 at 16:32