我正在尋找一種方法來保留我的句子的所有單詞,但第一個單詞。 我在紅寶石製成的:刪除句子的第一個詞
a = "toto titi tata"
a.gsub(a.split[0]+' ','')
=> 「塔塔蒂蒂」
是否有更好的東西?
我正在尋找一種方法來保留我的句子的所有單詞,但第一個單詞。 我在紅寶石製成的:刪除句子的第一個詞
a = "toto titi tata"
a.gsub(a.split[0]+' ','')
=> 「塔塔蒂蒂」
是否有更好的東西?
str = "toto titi tata"
p str[str.index(' ')+1 .. -1] #=> "titi tata"
代替使用gsub
的,該slice!
方法將移除指定的部分。
a = 'toto titi tata'
a.slice! /^\S+\s+/ # => toto (removed)
puts a # => titi tata
這裏有很多不錯的解決方案。我認爲這是一個體面的問題。 (即使它是一門功課或工作面試問題,它仍然值得討論)
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
乍看之下,似乎所有的解決方案都基本相同,只有語法/可讀性有所不同,但你可能會去的一種方式或其他如:
下降速度更快,但sub是現在最快的解決方案。 – andoke
gsub不會以這種方式工作。 – sawa