Split

What is the use of “split”?
for example if I have this variable : x=“1,2,3,4,5” , and I type
r=x.splite(’,’)
then type r , I will see [“1”, “2”, “3”, “4”, “5”].
And when I type t = x.split("-") ( or t=x.split("&") or any character at
the argument of split method ( else “,” ) ) I will see [“1,2,3,4,5”].
why this happen ?

2010/7/22 Amir E. [email protected]:

What is the use of “split”?

Use ri to summon the docs:

~>ri String.split
----------------------------------------------------------- String#split
str.split(pattern=$;, [limit]) => anArray

 Divides _str_ into substrings based on a delimiter, returning an
 array of these substrings.

 If _pattern_ is a +String+, then its contents are used as the
 delimiter when splitting _str_. If _pattern_ is a single space,
 _str_ is split on whitespace, with leading whitespace and runs of
 contiguous whitespace characters ignored.

 If _pattern_ is a +Regexp+, _str_ is divided where the pattern
 matches. Whenever the pattern matches a zero-length string, _str_
 is split into individual characters.

 If _pattern_ is omitted, the value of +$;+ is used. If +$;+ is
 +nil+ (which is the default), _str_ is split on whitespace as if `
 ' were specified.

 If the _limit_ parameter is omitted, trailing null fields are
 suppressed. If _limit_ is a positive number, at most that number of
 fields will be returned (if _limit_ is +1+, the entire string is
 returned as the only entry in an array). If negative, there is no
 limit to the number of fields returned, and trailing null fields
 are not suppressed.

    " now's  the time".split        #=> ["now's", "the", "time"]
    " now's  the time".split(' ')   #=> ["now's", "the", "time"]
    " now's  the time".split(/ /)   #=> ["", "now's", "", "the", 

“time”]
“1, 2.34,56, 7”.split(%r{,\s*}) #=> [“1”, “2.34”, “56”, “7”]
“hello”.split(//) #=> [“h”, “e”, “l”, “l”, “o”]
“hello”.split(//, 3) #=> [“h”, “e”, “llo”]
“hi mom”.split(%r{\s*}) #=> [“h”, “i”, “m”, “o”, “m”]

    "mellow yellow".split("ello")   #=> ["m", "w y", "w"]
    "1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]
    "1,2,,3,4,,".split(',', 4)      #=> ["1", "2", "", "3,4,,"]
    "1,2,,3,4,,".split(',', -4)     #=> ["1", "2", "", "3", "4", "", 

“”]

Cheers,

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs