ruby-on-rails - 为什么&运算符的输出与任何逻辑运算都不会在Ruby中给出任何输出?
问题描述
puts "Hello World"
scores = {"biology" => ['unit_test','final_exam'],
"maths" => ['quiz','class_participation','final_exam']
}
x = (scores["biology"] & %w[flying_test])
puts "result of x && scores[\"biology\"].any? => #{x && scores["biology"].any?}"# Why does this return true?
y = scores["maths"] & %w[quiz]
z = scores["maths"].any?
puts "result of scores[\"maths\"] & %w[quiz] => #{y}" # returns true
puts "result of scores[\"maths\"].any? => #{z}" # return true
puts "result of y && z => #{y && z}"
puts "******"
puts "Clubbing all conditions, returns no output, why? it is actually evluates to (true || true), right"
puts ( (scores["biology"].any? && (scores["biology"] & %w[flying_test])) ||
(scores["maths"].any? && (scores["maths"] & %w[quiz])) )
# But when above two sub-conditions are swapped puts print the value as true
puts "$$$$$$$"
puts ((scores["biology"] & %w[flying_test]) && scores["biology"].any?) ||
((scores["maths"] & %w[quiz]) && scores["maths"].any?)
puts "cross check"
# puts (1 == 1).any?
https://onlinegdb.com/YBmzutZOj - 你可以在这里执行
解决方案
&&
如果两个操作数都是truthy
,并且在ruby
空列表中是,则返回第二个操作数truthy
。
在您的特定情况下,x = (scores["biology"] & %w[flying_test])
评估为空 list []
,因此x && scores["biology"].any?
实际评估为[] && true
, so true
。
此外,在
puts ( (scores["biology"].any? && (scores["biology"] & %w[flying_test])) ||
(scores["maths"].any? && (scores["maths"] & %w[quiz])) )
第一个操作数的计算结果也为空列表,因此整个||
操作的计算结果为空列表[]
。执行puts []
结果不会生成任何输出。
推荐阅读
- pandas - 插值连续数
- c# - 将内部联接 Datagridview 导出到 Excel
- python - Mypy 错误:“重载的函数签名 2 永远不会匹配:签名 1 的参数类型相同或更宽”
- node.js - 在节点 js 中将 eval 选项设置为 true 时传递 workerData
- flutter - 我可以在下面的颤动代码中删除 const 吗?
- statistics - 使用 Fisher 精确检验、卡方检验测试独立性时的双边/单边特定目的
- sql - 如何在 SQL Server 中形成自定义 Json 对象
- c# - 我可以对已经定义了项目源的 DataGrid 中的复选框使用不同的项目源吗?
- flutter - 如何在 Flutter 中打开一次 ObjectBox 并跨多个页面访问
- wordpress - 为什么服务器在 WordPress 网站上找不到请求的页面?