私は私の文のすべての単語を保持する方法を探していますが、最初の単語を除きます。私はこれをルビーで作りました:
a = "toto titi tata"
a.gsub(a.split[0]+' ','')
=>「タタティティ」
もっと良いものはありますか?
私は私の文のすべての単語を保持する方法を探していますが、最初の単語を除きます。私はこれをルビーで作りました:
a = "toto titi tata"
a.gsub(a.split[0]+' ','')
=>「タタティティ」
もっと良いものはありますか?
正規表現を使用します。
a.gsub(/^\S+\s+/, '');
ここにはたくさんの素晴らしい解決策があります。これはまともな質問だと思います。(宿題や就職の面接の質問であっても、それでも議論する価値があります)
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
一見すると、すべてのソリューションは基本的に同じであり、構文/読みやすさだけが異なるように見えるかもしれませんが、次の場合はどちらか一方に進む可能性があります。
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