tags:

views:

111

answers:

6

Is there and way to write code like this in a way that makes what it does clearer?

a = (a.split(" ")[1..-1]).join(" ")

That deletes the first word of a sentence but the code doesn't look expressive at all.

+5  A: 

code

a = a.split[1..-1] * " "

explanation

String#split's default parameter is " "

Array * String is an alias for Array.join(String)

On second thought, I'm not sure if it's more transparent to someone who is not familiar with ruby, per se. But anyone who has worked with Ruby strings for a little bit will understand what's going on. And it's a lot more clean than the original version.


UPDATE

As per just-my-correct-opinion's answer (which you all should vote up instead of mine), if you are running Ruby 1.9.1 (which you should be, anyway) or Ruby 1.8.7, you can do:

a = a.split.drop(1) * " "
Justin L.
Don't cut yourself too short here. The only reason I know about `#drop` and `#drop_while` is because I've used them in Erlang and Haskell. Before I started with those, I used slices too.
JUST MY correct OPINION
+1  A: 

Somethink like following

a = a[a.index(' '), a.length-(a.index(' ')+1)]

No check though

Salil
You could be using `..`'s instead of `,`, and -1 instead of your last index, perhaps?
Justin L.
+5  A: 

for somebody who is used to reading rexep this is pretty clean:

a = a.sub(/^\S+\s/, "")

ymmv

bjelli
+1 pretty clean indeed.
Justin L.
+3  A: 

maybe making the process explicit will help

words = a.split
words.pop
a = words.join " "
bjelli
A good answer, but it removes the first element, not the last. Use shift instead of pop. (regex answer is still the best)
Joshua Cheek
+5  A: 
irb(main):024:0> "this is a test".split.drop(1) * " "
=> "is a test"

Edited to add:

Explanation:

  • By default #split delimits on whitespace.

  • #drop(1) gets rid of the first entry.

  • * " " does the same as #join(" ").

JUST MY correct OPINION
#drop, that's it :) I really need to start working in 1.9.1 more.
Justin L.
It's in 1.8.7 too (just tested that).
JUST MY correct OPINION
This one seem to be the most readable and terse one. Thanks!
celebrus
+2  A: 

And if you were using this throughout some code you might want to create the methods in String and Array to make your code readable. (works in 1.8.6 too)

class String
  def words
    split
  end
end

class Array
  def but_first
    self[1..-1]
  end
  def to_sentence
    join(' ')
  end
end

str = "And, this is a sentence"

puts str.words.but_first.to_sentence
Joc
I was paging down through the answers thinking of posting just this!
Bryan Ash