2012-09-21 54 views
1

我正在尋找一種方法來保留我的句子的所有單詞,但第一個單詞。 我在紅寶石製成的:刪除句子的第一個詞

a = "toto titi tata" 
    a.gsub(a.split[0]+' ','') 

=> 「塔塔蒂蒂」

是否有更好的東西?

+0

gsub不會以這種方式工作。 – sawa

回答

4

使用正則表達式。

a.gsub(/^\S­+\s+/, ''); 
+0

謝謝我這樣做:'a.sub(/^\ S + \ s + /,'')' – andoke

1
str = "toto titi tata" 
p str[str.index(' ')+1 .. -1] #=> "titi tata" 
1

代替使用gsub的,該slice!方法將移除指定的部分。

a = 'toto titi tata' 
a.slice! /^\S+\s+/ # => toto (removed) 
puts a    # => titi tata 
2

這裏有很多不錯的解決方案。我認爲這是一個體面的問題。 (即使它是一門功課或工作面試問題,它仍然值得討論)

這裏是我的兩種方法

a = "toto titi tata"  
# 1. split to array by space, then select from position 1 to the end 
a.split 
# gives you 
    => ["toto", "titi", "tata"] 
# and [1..-1] selects from 1 to the end to this will 
a.split[1..-1].join(' ') 

# 2. split by space, and drop the first n elements 
a.split.drop(1).join(' ') 
# at first I thought this was 'drop at position n' 
#but its not, so both of these are essentially the same, but the drop might read cleaner 

乍看之下,似乎所有的解決方案都基本相同,只有語法/可讀性有所不同,但你可能會去的一種方式或其他如:

  1. 你有一個很長的字符串處理
  2. 你被要求在不同的位置
  3. 下降的話
  4. 系統會要求您將文字從一個位置移動到另一個位置
+0

下降速度更快,但sub是現在最快的解決方案。 – andoke

相關問題