开发者

strange String.start_with? behaviour

I wrote a simple ruby script that reads URLs from a txt file and then开发者_如何学运维 downloads these files.

The txt file may contain comments which have a trailing # character.

I am reading the file line by line, chomp and strip each line and then check each line if it starts with a # sign.

Now I have the problem that line.start_with?("#") always returns false even though the line starts with a leading #.

I checked the characters and found out that at line[0] there is indeed no # character; it is at line[1].

Can sb. explain what is going on here? Has it st to do with the file's UTF-8 character encoding?

Thx!


Try using puts line.inspect to see whether there's anything in the string you haven't noticed.


you may want to try stripping first, eg

line.strip.start_with?("#")


You say that you're stripping the strings before checking things. But, I'm guessing that you're still getting leading whitespace. So, are you calling strip or strip!? The plain strip method returns the stripped string but does not change the string, the strip! version changes the string in place; if you're just using strip then you might be unknowingly throwing away the stripped string and then getting confused by the leading or trailing whitespace that is still there.

Similar issues may apply to your use of chomp when you want chomp!.

Furthermore, there's no need to use both chomp and strip, just strip (or strip!) is sufficient as chomp is, more or less, just a restricted version of rstrip which in turn is, essentially, just a strip applied to only the end of the string.


I found the reason for my problem: strange characters at beginning of file

...but not the solution.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜