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

时间:2018-06-07 11:33:52

标签: ruby ruby-on-rails-4

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

使用join会生成类似"1 || 2 || 3 || 4"的内容,但不会获得所需的输出。

1 个答案:

答案 0 :(得分:1)

除非API的文档特别接受用于查询的数组或“或”用于查询,否则无法执行此操作。

a || b将返回第一个“truthy”值,因此1 || 2将始终返回1,因为1是“truthy”(不是假,不是零)

您可以使用单独的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。