如何在 ruby 中使用 or(||) 运算符连接整数数组?



所以,情况是我有一个整数数组,比如[1,2,3,4]。 我必须查询与此api_query(x: 1 || 2 || 3 || 4)api_query(x: "1" || "2" || "3" || "4")类似的 api.我无法弄清楚如何实现这一目标。

使用 join 会产生类似这样的"1 || 2 || 3 || 4",它不会得到所需的输出。

除非 API 的文档专门接受用于查询的数组或用于查询的"or",否则您无法执行此操作。

a || b将返回第一个"真"值,因此1 || 2将始终返回 1,因为 1 是"真"(不假,不为零(

您可以通过单独的api_query调用来执行此操作。

def get_first_match(*array)
array.each do |element|
match_test = ap_query(x: element)
return match_test unless match_test['error'] # or whatever test for unsuccessful
end
nil
end

这让你做

my_result = get_first_match(1, 2, 3, 4)

my_result将包含第一个匹配项,如果未找到匹配项,则为 nil。

最新更新