如何用Ruby中的给定字符将字符串分割成两部分?

时间:2022-09-26 21:38:28

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

我们的应用程序是从使用Twitter登录的用户中挖掘名字。

Twitter is providing full names in a single string.

Twitter在一个字符串中提供全名。

Examples

例子

1. "Froederick Frankenstien"
2. "Ludwig Van Beethoven"
3. "Anne Frank"

I'd like to split the string into only two vars (first and last) based on the first " " (space) found.

我希望根据发现的第一个“”(空格)将字符串分割为两个vars (first和last)。

Example    First Name    Last Name 
1          Froederick    Frankenstein
2          Ludwig        Van Beethoven
3          Anne          Frank

I'm familiar with String#split but I'm not sure how to only split once. The most Ruby-Way™ (elegant) answer will be accepted.

我熟悉字符串#split,但我不知道如何只拆分一次。最ruby方式™(高雅)回答将被接受。

4 个解决方案

#1


131  

String#split takes a second argument, the limit.

字符串#split接受第二个参数,即极限。

str.split(' ', 2)

should do the trick.

应该足够了。

#2


12  

"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(" ")

#3


8  

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

split()的第二个参数指定要做多少次分割:

'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"]

#4


7  

Alternative:

选择:

    first= s.match(" ").pre_match
    rest = s.match(" ").post_match

#1


131  

String#split takes a second argument, the limit.

字符串#split接受第二个参数,即极限。

str.split(' ', 2)

should do the trick.

应该足够了。

#2


12  

"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(" ")

#3


8  

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

split()的第二个参数指定要做多少次分割:

'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"]

#4


7  

Alternative:

选择:

    first= s.match(" ").pre_match
    rest = s.match(" ").post_match