海外転職の面接で英語で聞かれるRubyとRailsの質問事例とそれを会話で対処する方法 - その2
移転しました。
前回のつづき。
【問題2】
What will val1 and val2 equal after the code below is executed? Explain your answer.
val1 = true and false val2 = true && false
もしすぐに答えが分かったとしても「え?なんか同じに見えるなー。この問題ってキミが考えたの?おもしろいなー」とか言って面接官をムダに調子に乗らせるのもいい。
【解答例2】
Although these two statements might appear to be equivalent, they are not, due to the order of operations. Specifically, the `and` and `or` operators have lower precedence than the `=` operator, whereas the `&&` and `||` operators have higher precedence than the `=` operator, based on order of operations.
To help clarify this, here’s the same code, but employing parentheses to clarify the default order of operations:
(val1 = true) and false # results in val1 being equal to true val2 = (true && false) # results in val2 being equal to false
この問題に関しても全ての演算子の優先順位を記憶しておく必要はない。たとえそれが暗記できていなくても「これって演算子の優先順位を問う問題だよね」と問題の骨格が指摘できればほぼOk。後は会話の流れで「=とandってどっちが上だったっけ?」とか聞けば、面接官も会話の中でどっちが上かぐらいは話し出す。最後は解答例にあるように()を付けたコード事例を示せば完璧。実際のコードにおいても()があった方が可読性が上がる。読む人に「演算子の優先順位を考慮させるコード」なんて優しさに欠ける。
この問題のポイントはそういう演算子の優先順位とかをまったく気にかけず「これはどう見ても同じ結果が返ってくるだろー!」とか言い出すレベルじゃないことを証明することだけ。
演算子の優先順位はこれ。
高い :: [] +(単項) ! ~ ** -(単項) * / % + - << >> & | ^ > >= < <= <=> == === != =~ !~ && || .. ... ?:(条件演算子) =(+=, -= ... ) not 低い and or
その3につづく。
海外転職の面接で英語で聞かれるRubyとRailsの質問事例とそれを会話で対処する方法 - その3 - Ruby on Railsのビシバシはぁはぁ日記
もっと詳しくエンジニア転職のコツとか書いてる本。
- 作者: Gayle Laakmann McDowell
- 出版社/メーカー: Wiley
- 発売日: 2014/09/02
- メディア: Kindle版
- この商品を含むブログ (3件) を見る