Xiaohu Li Xiaohu Li - 5 months ago 6x
Ruby Question

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

splits each letter ignoring spaces as in:

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

Why can
work this way?


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