从 zsh CLI 将数组作为输入变量传递到 Ruby 文件

Passing array as input variable into a Ruby file from zsh CLI

我正在编写一个从 zsh 调用的 ruby 文件,除其他外,我正在尝试将数组作为输入变量传递,如下所示:

ruby cim_manager.rb test --target=WhiteLabel --devices=["iPhone 8", "iPhone 12 Pro"]

在我的 ruby 文件中,我有一个函数:

# Generates a hash value from an array of arguments
#
# @param [Array<String>] The array of values. Each value of the array needs to separate the key and the value with "=". All "--" substrings will be replaced for empty substrings
#
# @return [Hash]
#
def generate_hash_from_arguemnts(args)
    hash = {}

    args.each{ |item|
        item = item.gsub("--", "")
        item = item.split("=")
        puts item.kind_of?(Array)
        hash[item[0].to_s] = item[1].to_s
    }

    return hash
end 

所以我可以得到这样的值:

{"target": "WhiteLabel", "devices": ["iPhone 8", "iPhone 12 Pro"]}

我在执行 Ruby 文件时遇到的错误是:

foo@Mac-mini fastlane % ruby cim_manager.rb test --target=WhiteLabel --devices=["iPhone 8", "iPhone 12 Pro"]
zsh: bad pattern: --devices=[iPhone 8,

有什么想法吗?

@ReimondHill:我看不出该错误与 Ruby 有何关联。您有一个 zsh 行,其中有 --devices= [...。执行 a

时可能会遇到相同的错误
echo --devices=["iPhone 8", "iPhone 12 Pro"]

左方括号是 zsh 通配符结构;例如,[aeiou] 是一个通配符,它​​试图匹配文件名中的人声。因此,此参数会尝试匹配工作目录中以名称 --devices= 开头的文件,因此您会收到类似 no matches found 的错误消息:- -设备=...。但是,有一个陷阱:[ ... ] 之间的字符列表必须 而不是 具有(未转义的)space。因此,您不会看到 未找到匹配项,而是 错误模式

毕竟,您不希望发生文件名扩展,而是将参数传递给您的程序。因此你需要引用它:

ruby .... '--devices=["iPhone 8", "iPhone 12 Pro"]'

罗纳德

根据@user1934428 的回答,我正在扩展我的 ruby 文件:

# Generates a hash value from an array of arguments
#
# @param [Array<String>] The array of values. Each value of the array needs to separate the key and the value with "=". All "--" substrings will be replaced for empty substrings
#
# @return [Hash]
#
def generate_hash_from_arguemnts(args)
    hash = {}

    args.each{ |item|
        item = item.gsub("--", "")
        item = item.gsub("\"", "")
        item = item.split("=")
        
        key = item[0].to_s
        
        value = item[1]
        if value.include?("[") && value.include?("]") #Or any other pattern you decide
            value = value.gsub("[","")
            value = value.gsub("]","")
            value = value.split(",")
        end
        
        hash[key] = value
    }

    return hash
end

然后是我的 zsh 行:

ruby cim_manager.rb test --target=WhiteLabel --devices='[iPhone 8,iPhone 12 Pro]'

来自 generate_hash_from_arguemnts 的 return 值打印:

{"target"=>"WhiteLabel", "devices"=>["iPhone 8", "iPhone 12 Pro"]}