1

私は私の文のすべての単語を保持する方法を探していますが、最初の単語を除きます。私はこれをルビーで作りました:

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

=>「タタティティ」

もっと良いものはありますか?

4

4 に答える 4

4

正規表現を使用します。

a.gsub(/^\S­+\s+/, '');
于 2012-09-21T14:50:44.190 に答える
2

ここにはたくさんの素晴らしい解決策があります。これはまともな質問だと思います。(宿題や就職の面接の質問であっても、それでも議論する価値があります)

これが私の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. 単語をある位置から別の位置に移動するように求められます
于 2012-09-21T15:56:50.470 に答える
1
str = "toto titi tata"
p str[str.index(' ')+1 .. -1] #=> "titi tata"
于 2012-09-21T14:51:37.747 に答える
1

を使用する代わりにgsubslice!メソッドは指定された部分を削除します。

a = 'toto titi tata'
a.slice! /^\S+\s+/ # => toto (removed)
puts a             # => titi tata
于 2012-09-21T15:09:16.097 に答える