如何在Ruby中使用给定字符将字符串拆分为仅两部分? [英] How to split string into only two parts with a given character in Ruby?
本文介绍了如何在Ruby中使用给定字符将字符串拆分为仅两部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们的应用程序正在从使用 Twitter 登录的人中挖掘姓名.
Our application is mining names from people using Twitter to login.
Twitter 在单个字符串中提供全名.
Twitter is providing full names in a single string.
示例
1. "Froederick Frankenstien"
2. "Ludwig Van Beethoven"
3. "Anne Frank"
我想根据第一个 " " 将字符串拆分为仅 两个 变量(
(空格)找到.first
和 last
)
I'd like to split the string into only two vars (first
and last
) based on the first " "
(space) found.
Example First Name Last Name
1 Froederick Frankenstein
2 Ludwig Van Beethoven
3 Anne Frank
我熟悉 String#split
但我不确定如何只拆分一次.将接受最 Ruby-Way™(优雅)的答案.
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.
推荐答案
String#split 接受第二个参数,即限制.
String#split takes a second argument, the limit.
str.split(' ', 2)
应该可以解决问题.
这篇关于如何在Ruby中使用给定字符将字符串拆分为仅两部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文