ruby start_with?(), end_with?()

19,246

Solution 1

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\|$/).

Solution 2

Did you try the RDoc?

"| LINKS |".start_with?("|") # => true
"| LINKS |".end_with?("|") # => true
Share:
19,246
thotheolh
Author by

thotheolh

Languages: Java - Pretty OK , Ruby - Learning , PHP - Learning , Python - Learning.

Updated on June 09, 2022

Comments

  • thotheolh
    thotheolh almost 2 years

    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