Split

A

Amir Ebrahimifard

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 ?
 
J

Jean-Julien Fleck

2010/7/22 Amir Ebrahimifard said:
What is the use of "split"?

Use ri to summon the docs:

~>ri String.split
----------------------------------------------------------- String#split
str.split(pattern=3D$;, [limit]) =3D> 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 #=3D> ["now's", "the", "time"]
" now's the time".split(' ') #=3D> ["now's", "the", "time"]
" now's the time".split(/ /) #=3D> ["", "now's", "", "the", "tim=
e"]
"1, 2.34,56, 7".split(%r{,\s*}) #=3D> ["1", "2.34", "56", "7"]
"hello".split(//) #=3D> ["h", "e", "l", "l", "o"]
"hello".split(//, 3) #=3D> ["h", "e", "llo"]
"hi mom".split(%r{\s*}) #=3D> ["h", "i", "m", "o", "m"]

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

Cheers,

--=20
JJ Fleck
PCSI1 Lyc=E9e Kl=E9ber
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top