加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – Split不返回空字符串

发布时间:2020-12-17 03:42:23 所属栏目:百科 来源:网络整理
导读:有没有办法获得: "[][][]".split('[]')#= ["","",""] 代替 #=[] 无需编写功能? 这种行为令人惊讶,因为有时irb会按预期响应: "[]a".split('[]')#=["","a"]` 解决方法 从 the docs开始: If the limit parameter is omitted,trailing null fields are suppr
有没有办法获得:

"[][][]".split('[]')
#=> ["","",""]

代替

#=>[]

无需编写功能?

这种行为令人惊讶,因为有时irb会按预期响应:

"[]a".split('[]')
#=>["","a"]`

解决方法

从 the docs开始:

If the limit parameter is omitted,trailing null fields are suppressed. If limit is a positive number,at most that number of fields will be returned (if limit is 1,the entire string is returned as the only entry in an array). If negative,there is no limit to the number of fields returned,and trailing null fields are not suppressed.

所以:

"[][][]".split("[]",-1)
# => ["",""]

这会产生四个空字符串,而不是你的三个字符串,但如果你考虑它,这是唯一有意义的结果.如果你在每个逗号上拆分,你也希望得到四个空字符串,因为在第一个逗号“之前”有一个空项,而在最后一个之后有一个“之后”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读