AKarpun
AKarpun

Reputation: 331

Ruby proper if structure

I'm working on a web scraper. There are few variants of a page, and the program should work a little bit differently on each. I need to alternate the way it processes pages depending on what are on the page. I can do nested ifs:

if str=data.css('div#imgTag').to_s
  str.delete('@') 
  #do something
elsif str=data.css('span#Title').to_s
  #do something else
elseif str=data.css('span#block').to_s
  #do something
end

return str

but the code above does not always work. I think there is a flaw, and I'm looking for a better way to address it. I'm looking for more elegant, construction.

Upvotes: 0

Views: 45

Answers (1)

Caillou
Caillou

Reputation: 1500

You can use a case when instead of if, it is more practical when your several ifs are about the same variable : http://www.techotopia.com/index.php/The_Ruby_case_Statement

Otherwise, I don't really know what you can do better. You should add more details about the context of your program and what's not working.

EDIT : @Aetherus is right in the comments, you're comparing using = instead of ==, which assigns a value to your variable instead of testing it, so it is always true.

EDIT AGAIN : @Stefan also have a point. If your data.css() returns nil, to_s will return an empty string which is always true. You can use try(:to_s) to return nil if called on a nil object (http://www.rubydoc.info/docs/rails/Object%3Atry).

Your code becomes :

case str
  when data.css('div#imgTag').try(:to_s)
    str.delete('@') 
    #do something
  when data.css('span#Title').try(:to_s)
    #do something else
  when data.css('span#block').try(:to_s)
    #do something
end

return str

Upvotes: 4

Related Questions