I can't see a practical difference between the boolean operators AND and OR in a Ruby case conditional.
我看不出布尔运算符与AND或Ruby条件句之间的实际区别。
For example, I want to get the user to input the sentence:
例如,我想让用户输入句子:
sudo make me a sandwich
And the case conditional starts as follows:
有条件的情况如下:
case user_selection
when /sudo/ && /sandwich/
However, if the user enters:
但是,如果用户输入:
make me a sandwich
The condition will be a satisfied.
这种情况将会令人满意。
My way around it in this instance is to re-order the conditions:
在这个例子中,我的方法是重新排列条件:
case user_selection
when /sandwich/ && /sudo/
But that pre-supposes that every time a user thinks to use "sudo" they will include the string "sandwich" in their response. However, this is functionally no different from this:
但这一假设前提是,每次用户想要使用“sudo”时,都会在响应中包含字符串“sandwich”。然而,这在功能上与此没有什么不同:
case user_selection
when /sudo/
I looked up boolean operators for Ruby conditionals, but have not found a satisfactory answer.
我查找了Ruby条件语句的布尔运算符,但没有找到满意的答案。
2 个解决方案
#1
6
You cannot use &&
in a case block like that, because when /sudo/ && /sandwich/
evaluates to just when /sandwich/
.
你不能在这样的情况块中使用&&,因为when /sudo/ & /sandwich/计算为when /sandwich/。
Instead you will need to use one regexp that looks for both words. A simple example might be:
相反,您需要使用一个regexp来查找这两个词。一个简单的例子可能是:
case user_selection
when /sudo.*sandwich/
#2
2
Just for reference.
仅供参考。
If you absolutely need a logical AND in your case statement, you could use a lambda :
如果你绝对需要一个符合逻辑的案例陈述,你可以使用lambda:
def answer(order)
case order
when ->(x) { x =~ /sudo/ && x =~ /sandwich/ }
puts 'Okay'
else
puts 'Do it yourself!'
end
end
answer 'make me a sandwich'
#=> Do it yourself!
answer 'sudo sing a song'
#=> Do it yourself!
answer 'sudo make me a sandwich'
#=> Okay
If you can compact the boolean logic to a single check (e.g. with a Regex), you probably should, as in @spickermann's answer.
如果您可以将布尔逻辑压缩到单个检查(例如使用Regex),那么您可能应该这样做,就像@spickermann的答案一样。
#1
6
You cannot use &&
in a case block like that, because when /sudo/ && /sandwich/
evaluates to just when /sandwich/
.
你不能在这样的情况块中使用&&,因为when /sudo/ & /sandwich/计算为when /sandwich/。
Instead you will need to use one regexp that looks for both words. A simple example might be:
相反,您需要使用一个regexp来查找这两个词。一个简单的例子可能是:
case user_selection
when /sudo.*sandwich/
#2
2
Just for reference.
仅供参考。
If you absolutely need a logical AND in your case statement, you could use a lambda :
如果你绝对需要一个符合逻辑的案例陈述,你可以使用lambda:
def answer(order)
case order
when ->(x) { x =~ /sudo/ && x =~ /sandwich/ }
puts 'Okay'
else
puts 'Do it yourself!'
end
end
answer 'make me a sandwich'
#=> Do it yourself!
answer 'sudo sing a song'
#=> Do it yourself!
answer 'sudo make me a sandwich'
#=> Okay
If you can compact the boolean logic to a single check (e.g. with a Regex), you probably should, as in @spickermann's answer.
如果您可以将布尔逻辑压缩到单个检查(例如使用Regex),那么您可能应该这样做,就像@spickermann的答案一样。