我正在寻找一种方法来保留我句子中的所有单词,但第一个单词除外。我用红宝石做的:
a = "toto titi tata"
a.gsub(a.split[0]+' ','')
=>“塔塔蒂蒂”
有更好的吗?
我正在寻找一种方法来保留我句子中的所有单词,但第一个单词除外。我用红宝石做的:
a = "toto titi tata"
a.gsub(a.split[0]+' ','')
=>“塔塔蒂蒂”
有更好的吗?
Use a regex.
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