andoke
andoke

Reputation: 184

Remove the first word of a sentence

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

Answers (4)

J_McCaffrey
J_McCaffrey

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)

Here are my two approaches

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:

  1. You have a really long string to deal with
  2. You are asked to drop words at different positions
  3. You are asked to move words from one position to another

Upvotes: 2

whirlwin
whirlwin

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

steenslag
steenslag

Reputation: 80065

str = "toto titi tata"
p str[str.index(' ')+1 .. -1] #=> "titi tata"

Upvotes: 1

xdazz
xdazz

Reputation: 160833

Use a regex.

a.gsub(/^\S­+\s+/, '');

Upvotes: 4

Related Questions