ruby 中的条件 case 没有进入 when

Case conditional in ruby doesn't enter in when

我的代码在执行时没有进入 case 条件内的 when 循环。 我想要的是根据函数的 *args 发送两个不同的 GET 请求。 因此,当我不发送请求中的参数之一时,我可以验证错误。 如果有人有更好的逻辑来用一种方法来做,我也很感激。

这是我的代码:

def get_function(access_token,order1,order2,*args)
    case args
      when  args = "order1"
        self.class.get("/v1/apiendpoint?order2=#{order2}",
                   headers: {'accesstoken': "#{access_token}"})
      when args = "order2"
        self.class.get("/v1/apiendpoint?order1=#{order1}",
                   headers: {'accesstoken': "#{access_token}"})
    end
  end

当我用 binding.pry 执行(调试)时,它显示了这部分,并且不执行其余代码。

From: C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-core-8.0.1/lib/cucumber/core/test/action.rb @ line 25 Cucumber::Core::Test::Action#execute:

22: def execute(*args)
23:   @timer.start
24:   @block.call(*args)
==> 25:   passed
26: rescue Result::Raisable => exception
27:   exception.with_duration(@timer.duration)
28: rescue Exception => exception
29:   failed(exception)
30: end

这里有多个问题:

case args
when  args = "order1"

首先,args 是一个 Array - 所以它不可能等于 String。我不确定你打算在这里发生什么,所以不能确切地说出如何解决它。

其次,= 是一个 赋值 运算符,而 == 执行相等性检查。

最后,这是一个 case 语句,而不是 if 语句,所以你实际上不应该在这里执行相等性检查......这些中的任何一个在语法上都是有意义的:

case args
when "order1"
   # ...
end

# OR:

case
when args == "order1"
  # ...
end

另外请注意,您的问题描述有点混乱。你说:

the when loop

但这不是循环。你可以称它为“子句”或“声明”,但它肯定不是“循环”。

在 Tom 的帮助下,决定采用 IF 语句。

这是有效的方法:

def get_function(access_token,order1,order2,*args)

 if args == ["order1"]
          self.class.get("/v1/apiendpoint?order2=#{order2}",
            headers: {'accesstoken': "#{access_token}"})
            else
              self.class.get("/v1/apiendpoint?order1=#{order1}",
                headers: {'accesstoken': "#{access_token}"})
        end

args 是一个 Array 参数,因此将它与 String 进行比较将始终计算为 false,而不管 String

我不确切知道你在函数行为方面需要什么,但我可以说的是,如果你想查看 args Array 将每个参数与 String 进行比较,在数组上 迭代 可能是更好的主意。

示例if

def args_example(*args)
  # Working directly with *args doesn't work, so we assign it to arguments
  arguments = *args

  # We need a way to save the output after the if clause
  output = []

  # Let's iterate!
  arguments.each do |argument|

    # This is where the if would come in
    if argument == "One"
      output << 1
    elsif argument == "Two"
      output << 2
    else
      output << 0
    end
  end

  output
end
args_example("One", "Two", "Three")

=> [1, 2, 0]

示例case

def args_example(*args)
  # Working directly with *args doesn't work, so we assign it to arguments
  arguments = *args
  
  # We need a way to save the output after the case clause
  output = []

  # Let's iterate!
  arguments.each do |argument|

    # This is where the case would come in
    case argument
    when "One"
      output << 1
    when "Two"
      output << 2
    else
      output << 0
    end
  end

  output
end
args_example("One", "Two", "Three")

=> [1, 2, 0]

这是一种检查提供给函数的所有参数的方法(肯定有更短的方法)并相应地发送GET请求。

干杯!

注意: 我保存了输出以便能够显示它,但我意识到因为你只执行了一个 GET 请求,所以你不需要需要这样做。只需执行请求而不是保存输出。