我有一个阵列
address = ["kuwait", "jordan", "United Arab Emirates", "Bahrain"]
location = "india"
order.country = "jordan"
address.include? (location || order.country) #=> false
Run Code Online (Sandbox Code Playgroud)
我的OR病情不在这里.请指导我错在哪里.
shi*_*vam 11
为什么你的代码不起作用
在下面的代码行中
address.include? (location || order.country)
Run Code Online (Sandbox Code Playgroud)
首先,location || order.country进行评估,"india"根据您的示例得出结果.然后它检查它是否存在于地址数组中,基本上是:
address.include? "india"
Run Code Online (Sandbox Code Playgroud)
这是false因为你得到false result.
同样,如果您尝试:
address.include? (order.country || location)
Run Code Online (Sandbox Code Playgroud)
它将true在检查时返回address.include? "jordan".因此,这不是实现目标的正确方法.
Array#include这个例子的正确使用方法是什么?
address.include?(location) || address.include?(order.country)
Run Code Online (Sandbox Code Playgroud)
有很多方法可以实现此功能:
!(address & [location, order.country]).empty?
(address & [location, order.country]).any?
[location, order.country].any? { |addr| address.include? addr }
Run Code Online (Sandbox Code Playgroud)
你的代码失败,因为location || order.country被评估为truthy(||在这种特殊情况下调用的第一个参数,因为"india"是truthy.)虽然你希望它被视为"数组包括这个或数组包含那个",但它实际上是"数组包括结果'this or that',显然"india"是给出的例子".
| 归档时间: |
|
| 查看次数: |
359 次 |
| 最近记录: |