3

I have a document with subject headers being enclosed in "|" characters.

E.g. "| LINKS |"

I want to check the string if it begins and ends with "|" character to verify that the particular document's subject header is valid. How do I do so ?

Source:

@filetarget = " < document file location here > "

@line = ""

file = File.new(@filetarget)

while (@line = file.gets)
   if((@line.start_with?("|")) and (@line.end_with?("|")))
      puts "Putting: " + @line
   end
end

Document text for parsing:

| LINKS |

http://www.extremeprogramming.org/  <1>

http://c2.com/cgi/wiki?ExtremeProgramming  <2>

http://xprogramming.com/index.php  <3>

| COMMENTS |

* Test comment
* Test comment 2
* Test comment 3
thotheolh
  • 7,040
  • 7
  • 33
  • 49

2 Answers2

19

Did you try the RDoc?

"| LINKS |".start_with?("|") # => true
"| LINKS |".end_with?("|") # => true
Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
  • @thotheolh: You should have said so in your question. Was it because you weren't using Ruby 1.9.2? (You can check by doing `puts RUBY_VERSION`) – Andrew Grimm Jun 18 '11 at 08:14
  • Is the 'starts_with' and 'end_with' affected by version ? irb(main):001:0> puts RUBY_VERSION 1.8.7 – thotheolh Jun 18 '11 at 08:19
  • @thoeolh: Yes. I don't think it's available in 1.9.1, or 1.8.7. – Andrew Grimm Jun 18 '11 at 08:29
  • 2
    @thotheloh: Both [`start_with?`](http://ruby-doc.org/core-1.8.7/classes/String.html#M000785) and [`end_with?`](http://ruby-doc.org/core-1.8.7/classes/String.html#M000786) are available in 1.8.7. So what exactly did you try? Do you have spaces at the beginning or end of your string? Or maybe a trailing newline? – mu is too short Jun 18 '11 at 08:39
  • You can at the older RDocs by starting from the homepage and navigating through all the frames. I'll bet you a beer that there is a [trailing newline](http://ruby-doc.org/core-1.8.7/classes/IO.html#M000585) on the string that's messing up the `end_with?` check. – mu is too short Jun 18 '11 at 08:45
  • 1
    @mu is too short: And if there's a newline or the like messing things up, the best way to find out is by doing `puts string.inspect` on the string. – Andrew Grimm Jun 18 '11 at 08:57
  • Or by noticing the `File.new("testfile").gets #=> "This is line one\n"` bit in the fine manual. But `inspect` is a good way to be sure. – mu is too short Jun 18 '11 at 09:03
6

You can just use a simple regular expression:

if line =~ /^\|.*\|$/

That way you can verify other things, like that the header has to be all caps and needs spaces around it (/^\|\s[A-Z]+\s\|$/).

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158