我在Ruby中有一个字符串变量,如下所示:
puts $varString.class
puts "##########"
puts $varString
Run Code Online (Sandbox Code Playgroud)
上面代码的输出是:
String
##########
my::FIrst::Line
this id second line
sjdf kjsdfh jsdf
djsf sdk fxdj
Run Code Online (Sandbox Code Playgroud)
我只需要从字符串变量中获取第一行(例如my::FIrst::Line).我怎么才能得到它?
Sim*_*tti 35
# Ruby >= 1.8.7
$varString.lines.first
# => "my::FIrst::Line"
# Ruby < 1.8.7
$varString.split("\n").first
# => "my::FIrst::Line"
Run Code Online (Sandbox Code Playgroud)
作为旁注,请避免使用全局($符号)变量.
Vic*_*gin 28
$varString.lines.first
Run Code Online (Sandbox Code Playgroud)
或者,如果您想在结果字符串中删除最终换行符:
$varString.lines.first.chomp
Run Code Online (Sandbox Code Playgroud)
first_line = str[/.*/]
就内存分配和性能而言,该解决方案似乎是最有效的解决方案。
这使用的str[regexp]形式,请参阅https://ruby-doc.org/core-2.6.5/String.html#method-i-5B-5D
基准代码:
require 'stringio'
require 'benchmark/ips'
require 'benchmark/memory'
str = "test\n" * 100
Benchmark.ips do |x|
x.report('regex') { str[/.*/] }
x.report('index') { str[0..(str.index("\n") || -1)] }
x.report('stringio') { StringIO.open(str, &:readline) }
x.report('each_line') { str.each_line.first.chomp }
x.report('lines') { str.lines.first }
x.report('split') { str.split("\n").first }
x.compare!
end
Benchmark.memory do |x|
x.report('regex') { str[/.*/] }
x.report('index') { str[0..(str.index("\n") || -1)] }
x.report('stringio') { StringIO.open(str, &:readline) }
x.report('each_line') { str.each_line.first.chomp }
x.report('lines') { str.lines.first }
x.report('split') { str.split("\n").first }
x.compare!
end
Run Code Online (Sandbox Code Playgroud)
基准测试结果:
Comparison:
regex: 5099725.8 i/s
index: 4968096.7 i/s - 1.03x slower
stringio: 3001260.8 i/s - 1.70x slower
each_line: 2330869.5 i/s - 2.19x slower
lines: 187918.5 i/s - 27.14x slower
split: 182865.6 i/s - 27.89x slower
Comparison:
regex: 40 allocated
index: 120 allocated - 3.00x more
stringio: 120 allocated - 3.00x more
each_line: 208 allocated - 5.20x more
lines: 5064 allocated - 126.60x more
split: 5104 allocated - 127.60x more
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17542 次 |
| 最近记录: |