Rubyのandと&&の違い
Rubyのandと&&の違い、覚えて忘れてを繰り返している気がするので今一度。
and
https://docs.ruby-lang.org/ja/latest/doc/spec=2foperator.html#and
左辺を評価し、結果が偽であった場合はその値(つまり nil か false) を返します。左辺の評価結果が真であった場合には右辺を評価しその結果を返します。 and は同じ働きをする優先順位の低い演算子です。
式1 and 式2
andの場合はまず式1が評価される。式1がfalseなら式2が評価される
fuga = true and false
p fuga
# => true
&&
&&の場合は 式1 && 式2 が評価され、その結果が返される
hoge = true && false
p hoge
# => false
以下のようなコードは num in -> {_1.even?} && num * 2 と書くとシンタックスエラーになる
&& で書くと num in -> {_1.even?} で完結せず右辺もまとめて評価されてしまうため、構文的におかしい
array = [1, 2, 3, 4]
array.filter_map {|num| num in -> {_1.even?} && num * 2}
# => syntax error, unexpected &&, expecting '}' (SyntaxError)
# andならOK
array.filter_map {|num| num in -> {_1.even?} and num * 2}