Reputation: 184
I am looking for a way to keep all the words of my sentence but the first one. I made this in ruby :
a = "toto titi tata"
a.gsub(a.split[0]+' ','')
=> "tata titi"
Is there something better ?
Upvotes: 1
Views: 1827
Reputation: 1455
Lots of nice solutions here. I think this is a decent question. (even if it is a homework or job interview question, its still worth discussing)
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
At first glance it might seem that all of the solutions are basically the same, and only differ by syntax/readability, but you might go one way or the other if:
Upvotes: 2
Reputation: 16521
Instead of using gsub
, the slice!
method will remove the part specified.
a = 'toto titi tata'
a.slice! /^\S+\s+/ # => toto (removed)
puts a # => titi tata
Upvotes: 1
Reputation: 80065
str = "toto titi tata"
p str[str.index(' ')+1 .. -1] #=> "titi tata"
Upvotes: 1