#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2009
    Posts
    5
    Rep Power
    0

    Concatenation problem


    Newbie question. I have a text file with a bunch of urls that look, let's say, like this:
    yahoo/Business_%26_Finance/Stocks_A/index.html

    I need to add a "prefix" and "suffix" so was doing this:

    datafile.readlines.each {|url|

    companyURL = "http://".concat(url.to_s).concat("?off=1")
    puts companyURL
    }

    But the result has a line break in it before the "suffix"

    http://yahoo/Business_%26_Finance/Stocks_A/index.html
    ?off=1

    How do I get it to concatenate into one line?
    TIA
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2004
    Location
    Constant Limbo
    Posts
    989
    Rep Power
    363
    The operator/method you are looking for is chomp. See the following example:
    Code:
    irb(main):001:0> s = "yahoo/Business_%26_Finance/Stocks_A/index.html\n"
    => "yahoo/Business_%26_Finance/Stocks_A/index.html\n"
    irb(main):002:0> "http://" + s.chomp + "?off=1"
    => "http://yahoo/Business_%26_Finance/Stocks_A/index.html?off=1"
    It is due to that fact that when you read a line in from user or file you get the newline (\n) with it.
    What makes this kind of tricky in ruby (and I find it to be particularly pesky) is that puts is nice enough to strip that newline for you if it is at the end of your string.
    Code:
    irb(main):003:0> s = "some new string\n"
    => "some new string\n"
    irb(main):004:0> puts s
    some new string
    => nil
    irb(main):005:0> s = "some new string\n\n"
    => "some new string\n\n"
    irb(main):006:0> puts s
    some new string
    
    => nil
    So if you try to debug this problem by tracer bullets (outputting to console) it magically disappears.
    True happiness is not getting what you want, it's wanting what you've already got.

    My Blog
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2009
    Posts
    5
    Rep Power
    0
    Thanks!
    I just figured out that .strip was working also but I was still clueless as to why I wasn't seeing the problem. Now I get it!

IMN logo majestic logo threadwatch logo seochat tools logo