Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between // and ''

Tags:

ruby

  1. What is the difference between // and '' here?

    123.to_s.split(//)  #=> ["1", "2", "3"]
    123.to_s.split('')  #=> ["1", "2", "3"]
    

    Both give the same result.

  2. What is // for?

like image 221
shin Avatar asked Sep 15 '26 05:09

shin


2 Answers

Q1: '' is an empty String, whereas // is an empty Regexp:

2.0.0p247 :001 > ''.class
# => String 

2.0.0p247 :002 > //.class
# => Regexp 

String#split happens to accept both Strings and Regexp objects when deciding what to split on. Because adding an empty String to a String doesn't change the string, the string can be thought of as '1' + '' + '2' + '' + '3'. Splitting against the empty string, therefore, will break the original string into individual characters.

Similarly, an empty Regexp matches any position next to a character, so split splits on every character in this case too. That's why they have the same result.

Q2 I can't think of many (any?) uses for an empty Regexp :)

EDIT: @sawa is correct. Humbly updated.

like image 189
andrewdotnich Avatar answered Sep 16 '26 20:09

andrewdotnich


1 '' is a string, and // is a regular expression.

Any position in a string adjacent to a character can be assumed to implicitly include ''. In other words, adding '' to a position in a string does not change the content of the string:

'' + 'foo' # => 'foo'
'foo' + '' + 'bar' # => 'foobar'
'foo' + 'bar' # => 'foobar'
'foo' + '' # => 'foo'

Therefore, a string 'abc' can be considered to be 'a' + '' + 'b' + '' + 'c', and hence, splitting 'abc' by '' results in ['a', 'b', 'c'].

Similarly, any position in a string adjacent to a character matches //. Therefore, splitting 'abc' by // results in ['a', 'b', 'c'].

2 The particular regex // may not be useful, but regexes in general are useful, and there is no reason to particularly prohibit //.

like image 43
sawa Avatar answered Sep 16 '26 20:09

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!