Split string by multiple delimiters

后端 未结 5 1481
迷失自我
迷失自我 2020-12-08 01:52

I want to split a string by whitespaces, , and \' using a single ruby command.

  1. word.split will split by white spaces

5条回答
  •  被撕碎了的回忆
    2020-12-08 02:28

    You can use a combination of the split method and the Regexp.union method like so:

    delimiters = [',', ' ', "'"]
    word.split(Regexp.union(delimiters))
    # => ["Now", "is", "the", "time", "for", "all", "good", "people"]
    

    You can even use regex patters in the delimiters.

    delimiters = [',', /\s/, "'"]
    word.split(Regexp.union(delimiters))
    # => ["Now", "is", "the", "time", "for", "all", "good", "people"]
    

    This solution has the advantage of allowing totally dynamic delimiters or any length.

提交回复
热议问题