开发者

How can I write this so it's easier to understand?

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.


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(" ").


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

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

ymmv


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) * " "


maybe making the process explicit will help

words = a.split
words.pop
a = words.join " "


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


Something like following

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

No check though

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜