Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby/Rails if/else case语句_Ruby - Fatal编程技术网

Ruby/Rails if/else case语句

Ruby/Rails if/else case语句,ruby,Ruby,我在lib方法中有以下if-else语句: begin url = URI.parse("url"+ product ) @response = JSON.parse(Net::HTTP.get_response(url).body) url2 = URI.parse("url" + product) @response1 = JSON.parse(Net:

我在lib方法中有以下if-else语句:

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,如果@response=nil,则跳过该方法。如何检查@response是否为nil,如果是,则使用url2和@response1并保存从该响应返回的变量。如果@response不是nil,则保存@response返回的变量


@response和@response1是不同的API

我想这就是你想要的。关键是要检查nil,请使用@response.nil?另一个问题是,如果它第一次失败,你会得到相同的url——不知道为什么你会再次要求相同的url,如果它第一次失败,你会以不同的方式对待它

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

  if !@response.nil?
    @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

URI.parse(“url+产品)
您似乎有语法错误……url和url2以及@response和@response1之间有什么区别?我认为问题在于
JSON.parse
从不返回nil。我在文档中找不到,但我无法让它返回nil。