How to split string into only two parts with a given character in Ruby?

前端 未结 4 1784
生来不讨喜
生来不讨喜 2020-12-29 19:42

Our application is mining names from people using Twitter to login.

Twitter is providing full names in a single string.

Examples

1. \"Froeder         


        
相关标签:
4条回答
  • 2020-12-29 19:57

    String#split takes a second argument, the limit.

    str.split(' ', 2)
    

    should do the trick.

    0 讨论(0)
  • 2020-12-29 20:00

    The second argument of .split() specifies how many splits to do:

    'one two three four five'.split(' ', 2)
    

    And the output:

    >> ruby -e "print 'one two three four five'.split(' ', 2)"
    >> ["one", "two three four five"]
    
    0 讨论(0)
  • 2020-12-29 20:02

    Alternative:

        first= s.match(" ").pre_match
        rest = s.match(" ").post_match
    
    0 讨论(0)
  • 2020-12-29 20:03
    "Ludwig Van Beethoven".split(' ', 2)
    

    The second parameter limits the number you want to split it into.

    You can also do:

    "Ludwig Van Beethoven".partition(" ")
    
    0 讨论(0)
提交回复
热议问题