如何去除最後一個單元?例如,我有一個字符串像這樣:如何從句子中移除最後一個單詞(字符串)
str1 = "My testing String"
str2 = "My another testing string"
我需要顯示輸出的一種巧妙的方法:
str1 = "My testing"
str2 = "My another testing"
這是我能做什麼:
str1 = str1.split(" ")
str1.delete(str1.last)
str1.join(" ")
# => "My testing"
我想知道如果有任何干淨的做法可能在一行中,例如:str.split(" ", 2).last => "testing string"
,而應顯示"my testing"
。
編輯
謝謝你的多,有趣的答案傢伙。我感謝你的努力和時間。但是,我必須公平,所以我決定以大家的答案爲基準。下面是基準報告:這清楚地表明,答案p str2[0...str2.rindex(' ')]
表現良好
#!/usr/bin/ruby
require 'benchmark'
str2 = "My another testing string"
n = 500
Benchmark.bm(20) do |x|
x.report("str2[/(.*)\s/,1] "){ n.times { str2[/(.*)\s/,1] } }
x.report("str2[0...str2.rindex(' ')] "){ n.times { str2[0...str2.rindex(' ')] } }
x.report("str2.split(' ')[0...-1].join(' ') "){ n.times { str2.split(' ')[0...-1].join(' ') } }
x.report("str2[/.*(?=\s)/] "){ n.times { str2[/.*(?=\s)/] } }
end
user system total real
str2[/(.*) /,1] 0.000000 0.000000 0.000000 ( 0.001394)
str2[0...str2.rindex(' ')] 0.000000 0.000000 0.000000 ( 0.000956)
str2.split(' ')[0...-1].join(' ') 0.010000 0.000000 0.010000 ( 0.002569)
str2[/.*(?=)/] 0.000000 0.000000 0.000000 ( 0.001351)
。雖然我也喜歡其他方法,非常體貼和有趣。謝謝。
第二版
按這裏@theTineMan評論是更新的基準:
require 'benchmark'
str2 = "My another testing string"
n = 999999
Benchmark.bmbm(20) do |x|
x.report("str2[/(.*)\s/,1] "){ n.times { str2[/(.*)\s/,1] } }
x.report("str2[0...str2.rindex(' ')] "){ n.times { str2[0...str2.rindex(' ')] } }
x.report("str2.split(' ')[0...-1].join(' ') "){ n.times { str2.split(' ')[0...-1].join(' ') } }
x.report("str2[/.*(?=\s)/] "){ n.times { str2[/.*(?=\s)/] } }
end
Rehearsal ----------------------------------------------------------------------
str2[/(.*) /,1] 1.030000 0.000000 1.030000 ( 1.033787)
str2[0...str2.rindex(' ')] 0.850000 0.000000 0.850000 ( 0.853124)
str2.split(' ')[0...-1].join(' ') 4.740000 0.000000 4.740000 ( 4.750215)
str2[/.*(?=)/] 0.990000 0.000000 0.990000 ( 0.990726)
------------------------------------------------------------- total: 7.610000sec
user system total real
str2[/(.*) /,1] 1.020000 0.000000 1.020000 ( 1.014772)
str2[0...str2.rindex(' ')] 0.830000 0.000000 0.830000 ( 0.839385)
str2.split(' ')[0...-1].join(' ') 4.620000 0.010000 4.630000 ( 4.629874)
str2[/.*(?=)/] 0.990000 0.000000 0.990000 ( 0.988224)
你的基準測試顯示,你沒有運行足夠的測試得出確鑿的答案。增加你的'n'循環,直到它最慢需要一秒鐘,結果將意味着更多。後臺任務目前對您的號碼影響過大。 –
@theTinMan當然,我會這樣做,並更新相同的。 – Surya