2010-06-26 60 views

回答

5
irb(main):024:0> "this is a test".split.drop(1) * " " 
=> "is a test" 

編輯添加:

說明:

  • 默認情況下#split劃上的空白。

  • #drop(1)擺脫第一個條目。

  • * " "#join(" ")的做法相同。

+0

#drop,就是這樣:)我真的需要開始工作在1.9.1以上。 – 2010-06-26 09:40:16

+0

它也在1.8.7(只是測試)。 – 2010-06-26 09:47:10

+0

這似乎是最可讀和最簡潔的一個。謝謝! – vikhyat 2010-06-26 09:48:59

5

代碼

a = a.split[1..-1] * " " 

解釋

String#split的默認參數爲 「」

Array * StringArray.join(String)

別名

關於第二個想法,我不確定是否更透明對不熟悉ruby的人本身。但任何使用Ruby字符串的人都會明白髮生了什麼。它比原始版本更乾淨。


UPDATE

just-my-correct-opinion的回答(你都應該投票了,而不是我的),如果你正在運行1.9.1(你應該是,反正)或Ruby 1.8。 7,你可以這樣做:

a = a.split.drop(1) * " " 
+0

不要在這裏縮短自己太短。我知道'#drop'和'#drop_while'的唯一原因是我在Erlang和Haskell中使用過它們。在開始使用這些之前,我也使用了切片。 – 2010-06-26 10:18:02

1

喜歡的東西下面

a = a[a.index(' '), a.length-(a.index(' ')+1)] 

無校驗雖然

+1

您可以使用'..'而不是','和-1而不是最後一個索引,也許? – 2010-06-26 09:35:59

5

的人誰是用來閱讀rexep這是很乾淨:

a = a.sub(/^\S+\s/, "") 

因人而異

+0

確實很乾淨。 – 2010-06-26 09:36:15

3

可能使該過程的明確將有助於

words = a.split 
words.pop 
a = words.join " " 
+0

一個很好的答案,但它刪除了第一個元素,而不是最後一個元素。使用移位而不是彈出。 (正則表達式的答案仍然是最好的) – 2010-06-26 09:50:33

2

如果你使用這個遍及一些代碼,您可能要創建的字符串和數組的 方法,使你的代碼的可讀性。 (工作在1.8.6)

class String 
    def words 
    split 
    end 
end 

class Array 
    def but_first 
    self[1..-1] 
    end 
    def to_sentence 
    join(' ') 
    end 
end 

str = "And, this is a sentence" 

puts str.words.but_first.to_sentence 
+0

我正在尋找答案,想要發佈這個! – 2010-06-27 02:44:30