Xiaohu Li Xiaohu Li - 2 years ago 111
Ruby Question

The meaning of `split(%r{\s*})`

split(%r{\s*})
splits each letter ignoring spaces as in:

"hi mom".split(%r{\s*}) # => ["h", "i", "m", "o", "m"]


Why can
%r{\s*}
work this way?

Answer Source

%r{...} (or %r[...], or %r#....#, or %rX...X... you get the gist) is equivalent to /.../, a RegExp literal. In a regular expression, \s is a space, and * is 0 or more of preceding token: together, the expression says "split the string at every point there is zero or more spaces". There is zero or more spaces between each character of the string (aside from the space, which gets swallowed as the recognised delimiter).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download