我有三个包含不同主机名集的数组:
webserver = [
"ws1.xyz.com",
"ws2.xyz.com",
"ws3.xyz.com"
]
dbserver = [
"db1.xyz.com",
"db2.xyz.com",
"db3.xyz.com"
]
appserver = [
"app1.xyz.com",
"app2.xyz.com",
"app3.xyz.com"
]
我想在其中一个运行脚本的数组中识别当前主机。到目前为止,这就是我所拥有的:
require "socket"
host_name = Socket::gethostname
if webserver.grep(/#{host_name}/)
puts "You're a web server"
elsif dbserver.grep(/#{host_name}/)
puts "You're a db server"
elsif appserver.grep(/#{host_name}/)
puts "You're an app server"
else
puts "You're not in any group"
end
它始终与第一个if
块匹配。
答案 0 :(得分:3)
不确定为什么会得到这个结果,但更好的方法是:
case Socket.gethostname
when *webserver then puts "You're a web server"
when *dbserver then puts "You're a db server"
when *appserver then puts "You're an app server"
else puts "You're not in any group"
end
答案 1 :(得分:2)
问题是Enumerable#grep
总是返回一个数组。即使找不到该值,它也只会返回一个空数组。在Ruby中,除false
和nil
之外的所有值都被认为是假的。因此,无论你在哪里和哪里,
if array.grep(/something/)
# do something
end
始终会执行 do something
。至于做什么 - 你可以对结果进行Array#empty?
检查,但@sawa's answer是最惯用的方式。
答案 2 :(得分:-1)
真正简单的方法是......
if webserver.include?(host_name)
...