Victor S
Victor S

Reputation: 5142

How do I suppress string interpolation issues in ruby

I have the following code:

address = "#{(article/"div.address").inner_html.strip_html.squish}"

(using Hpricot)

And in some instances...

address = "#{(article/"div.address").inner_html.strip_html.squish}"

...is nil

I would like the script to keep chugging along, possibly replacing nil with an empty string.

Any tips?

Edit

I have traced the problem better to:

puts "#{link[0].to_s}\n" unless link.empty?

(.backtrace points to this particular line in the source.)

So the revised question is: why doesn't that line just not get parsed? Why does it throw an error? I thought that using unless will just skip it...

Upvotes: 1

Views: 516

Answers (3)

Victor S
Victor S

Reputation: 5142

Thank you all for the support and helpful tips, in the end it was a matter of using the proper method, I ended up solving my problem by using:

unless uri.query.nil?

But I did come to make use of both .to_s and try in my source, and I wish I could pick two answers as the right one!

Upvotes: -1

deviousdodo
deviousdodo

Reputation: 9172

Is try what you are looking for? http://api.rubyonrails.org/classes/Object.html#method-i-try

Upvotes: 0

Oleksandr Skrypnyk
Oleksandr Skrypnyk

Reputation: 2830

Use :to_s method:

nil.to_s == ''

Upvotes: 2

Related Questions