我正在寻找一种方法来保留我的句子的所有单词,但第一个。 我用红宝石做了这个:
a = "toto titi tata"
a.gsub(a.split[0]+' ','')
=> “tata titi”
还有更好的东西吗?
答案 0 :(得分:4)
使用正则表达式。
a.gsub(/^\S+\s+/, '');
答案 1 :(得分: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
乍一看似乎所有解决方案基本相同,只是语法/可读性不同,但如果出现以下情况,您可能会采用这种方式:
答案 2 :(得分:1)
str = "toto titi tata"
p str[str.index(' ')+1 .. -1] #=> "titi tata"
答案 3 :(得分:1)
gsub
方法不会使用slice!
,而是删除指定的部分。
a = 'toto titi tata'
a.slice! /^\S+\s+/ # => toto (removed)
puts a # => titi tata