gpt4 book ai didi

Ruby 将我的变量视为注释

转载 作者:太空宇宙 更新时间:2023-11-03 17:38:24 25 4
gpt4 key购买 nike

完全披露:我并不真正了解 Ruby。我主要是在假装。

我有一个脚本,我想用它来收集 Casper 中的库存,我用它来管理一堆 Mac。我正在尝试使用 %x 将变量传递到 shell 命令。问题是,Ruby 将变量视为注释。相关代码如下:

def get_host
host=%x(/usr/sbin/dsconfigad -show | /usr/bin/awk '/Computer Account/ {print $4}').chomp
raise Error, "this machine must not be bound to AD.\n try again." if host == nil
end

def get_ou
host = get_host
dsout = %x(/usr/bin/dscl /Search -read /Computers/#{host}).to_a
ou = dsout.select {|item| item =~ /OU=/}.to_s.split(",")[1].to_s.gsub(/OU=/, '').chomp
end

我尝试使用反引号代替 %x,但得到了相同的结果。该命令应该返回有关其运行的主机的一堆信息,但它返回的是 dscl/Search -read/Computers 的结果,它始终是 name: dsRecTypeStandard:Computers.

我怎样才能完成我想做的事?

最佳答案

问题就在这里。 Ruby 始终返回方法中的最后一个表达式。

def get_host
host=%x(/usr/sbin/dsconfigad -show | /usr/bin/awk '/Computer Account/ {print $4}').chomp
raise Error, "this machine must not be bound to AD.\n try again." if host == nil
end

在这种情况下,最后一个表达式是:

raise Error, "this machine must not be bound to AD.\n try again." if host == nil

如果 host == nil 或将返回 nil,它将返回 raise 的返回值(实际上不会发生)如果 host != nil。所以你的方法永远不会返回 nil 以外的东西。替换为:

def get_host
host=%x(/usr/sbin/dsconfigad -show | /usr/bin/awk '/Computer Account/ {print $4}').chomp
raise Error, "this machine must not be bound to AD.\n try again." if host == nil
host
end

关于Ruby 将我的变量视为注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10524025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com