首页 > 解决方案 > 为什么&运算符的输出与任何逻辑运算都不会在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 - 你可以在这里执行

标签: ruby-on-railsrubybitwise-operators

解决方案


&&如果两个操作数都是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 []结果不会生成任何输出。


推荐阅读