[英]Exit code from with Ruby + rest client
I learning ruby and playing it with restsclient I have following test the code and I'm expecting that to return 1/false. 我学习了ruby并与restsclient一起玩,我已经对代码进行了以下测试,并且期望它返回1 / false。 I can't seem to make it work.
我似乎无法使其工作。
n@lap-jta102:~/tsamcode$ ./get.rb
n@lap-jta102:~/tsamcode$ echo $?
0
#!/usr/bin/env ruby
require 'rest_client'
require 'json'
begin
response = RestClient.get("https://admin:admin@172.16.210.10/isam/host_records/187.0.0.1/hostnames", :content_type => :json, :accept => :json)
return true if response.code == 200
rescue => e
return false unless response != 200
end
$?
is not set by return
, but by exit
. 不是由
return
设置的,而是由exit
。 In fact, your return
doesn't even do what you think. 实际上,您的
return
甚至没有您的想法。 Try just this: 试试这个:
# one-returner.rb
return 1
$ ruby one-returner.rb
one-returner.rb:1:in `<main>': unexpected return (LocalJumpError)
The reason you're not getting an error in your program is the fact that you blanket-rescue this error when raised by return true
(since you have an unrestricted rescue
, which is a bad practice for exactly this reason, it can catch a wrong thing and leave you puzzled), and return false
never executes (and thus never raises an error) due to unless
. 您的程序中没有出现错误的原因是,当您通过
return true
引发该错误时,您可以一揽子地解决该错误(由于您具有不受限制的rescue
,因此,这是错误的做法,因为它可能会导致错误东西,让你困惑),并return false
从不执行(并因此永远不会引发错误),由于unless
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.