2013-02-04 71 views
-1

,我有以下如果一个lib方法else语句:的Ruby/Rails的if/else case语句

begin 
    url     = URI.parse("url"+ product) 
    @response   = JSON.parse(Net::HTTP.get_response(url).body) 
    url2     = URI.parse("url" + product) 
    @response1   = JSON.parse(Net::HTTP.get_response(url2).body) 

    if @response != nil 
     @url     = @response["product"]["url"] 
     image_url1   = @response["product"]["image_url"] 
     @title    = @response["product"]["title"] 

    else 
     @url     = @response1["ProductUrl"] 
     @image_url   = @response1["ImagePath"] 
     @title    = @response1["ProductName"] 
    end 
    rescue 
    next 
end 

目前这种方法只检查URL和@应答,并且简单地跳过如果@应答=零。如何检查@response是否为零,如果是,请使用url2和@ response1并保存从该响应返回的变量。如果@response不为零,请保存@respoonse返回的变量。

@应答和@响应1是不同的API

+1

'URI.parse(“网址+产品)'你似乎有一个语法错误... –

+0

哎呀,固定的,谢谢! – Yogzzz

+0

什么的URL和url2和@应答和@响应1? – Andy

回答

2

我想这是你想要的。关键是要检查零,使用@ response.nil?另一个问题是,看到的是,如果它第一次失败,你会得到相同的网址 - 不知道为什么你会再次要求相同的网址,并且如果第一次失败,就会以不同的方式处理它。

begin 
    url = URI.parse("url+ product) 
    @response = JSON.parse(Net::HTTP.get_response(url).body) 

    if [email protected]? 
    @url = @response["product"]["walmart_canonical_url"] 
    @image_url = @response["product"]["image_url"] 
    @title = @response["product"]["title"] 
    else 
    url = URI.parse("url" + product) 
    @response = JSON.parse(Net::HTTP.get_response(url2).body) 
    @url = @response["ProductUrl"] 
    @image_url = @response["ImagePath"] 
    @title = @response["ProductName"] 
    end 

rescue 
    next 
end