【发布时间】:2021-05-28 17:12:00
【问题描述】:
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 中不返回true/false,它返回最后评估的值。a && b包含表达式a和表达式b。a总是被评估。如果a的计算结果为假值(nil或false),则表达式短路并返回a的结果。如果a的计算结果为真值(不是false或nil),则计算表达式b并返回b的结果。以下是一些示例:true && true #=> true、true && 1 #=> 1、1 && 'Hello World!' #=> "Hello World!"、false && 1 #=> false、nil && 1 #=> nil、2 && nil #=> nil
标签: ruby-on-rails ruby bitwise-operators