简体   繁体   English

Ruby:我可以在一个语句中多次使用“或”(||)吗?

[英]Ruby: Can I use “or”( || ) more than once in one statement?

Hi I'm trying to make a blackjack game using Ruby and am trying to make the values of the picture cards all = 10. Is it okay to use the code I use below to accomplish this? 嗨,我正在尝试使用Ruby进行二十一点游戏,并试图使图片卡的值全部= 10.是否可以使用我在下面使用的代码来完成此操作? (this is all happening in my Card class) (这都发生在我的Card课程中)

def value
  if @number == ("jack" || "queen" || "king")
    10
  else
    @number.to_i
  end
end

You can, but not the way you are using it. 你可以,但不是你使用它的方式。 You either need to use the entire boolean expression in each portion: 您需要在每个部分中使用整个布尔表达式:

if @number == "jack" || @number == "queen" || @number == "king"

or you can make it simpler by checking the contents of an array: 或者你可以通过检查数组的内容使它更简单:

if ["jack", "queen", "king"].include?(@number)

The parens group things that should be evaluated before other things. parens将在其他事情之前应该评估的事情分组。 So, the above says, evaluate: 所以,上面说,评价:

 ("jack" || "queen" || "king")

and return the results. 并返回结果。 Lets try that in irb: 让我们尝试在irb中:

irb(main):004:0> ("jack" || "queen" || "king")
=> "jack"

Since "jack" is truthy there's no need to look at the rest of the list and "jack" is returned. 由于“jack”是真的,所以不需要查看列表的其余部分并返回“jack”。

This will work fine as long as @number is equal to "jack" but not so much for the other values. 只要@number等于“jack”,这种方法就可以正常工作,但对其他值则没有那么多。 You want to compare @number against each value until you get a match or exhaust the list. 您希望将@number与每个值进行比较,直到您获得匹配或耗尽列表。 See @PinneyM's answer of 请参阅@PinneyM的回答

(@number == "jack") || (@number == "queen") ...

That is a valid ruby snippet, but it doesn't do what you think it does: it first evaluates 这是一个有效的ruby片段,但它没有按照你的想法做到:它首先进行评估

 ("jack" || "queen" || "king")

which evaluates to "jack" as that is the first non false/nil value. 评估为“jack”,因为这是第一个非假/零值。 It then compares @card to this, so your code is equivalent to 然后将@card与此进行比较,因此您的代码相当于

def value
  if @number == 'jack'
    10
  else
    @number.to_i
  end
end

You could compare each in turn (@number == 'jack') || (@number == 'queen') ||... 您可以依次比较每个(@number == 'jack') || (@number == 'queen') ||... (@number == 'jack') || (@number == 'queen') ||... , you could use %w(jack queen king).include?(@number) or you could use a case statement: (@number == 'jack') || (@number == 'queen') ||... ,你可以使用%w(jack queen king).include?(@number)或者你可以使用case语句:

def value
  case @number
  when 'jack', 'queen', 'king'
    10
  else
    @number.to_i
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM