gpt4 book ai didi

ruby - 在 Ruby 语言中,如何获取字符串中的行数?

转载 作者:数据小太阳 更新时间:2023-10-29 06:27:05 24 4
gpt4 key购买 nike

在Ruby语言中,如何获取字符串中的行数?

最佳答案

字符串有一个lines 方法,它返回一个Enumerator。在枚举器上调用 count

str = "Hello\nWorld"
str.lines.count # 2

str = "Hello\nWorld\n" # trailing newline is ignored
str.lines.count # 2

lines 方法是在 Ruby 1.8.7 中引入的。如果您使用的是旧版本,请查看@mipadi 和@Greg 的回答。

关于ruby - 在 Ruby 语言中,如何获取字符串中的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2590053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com