2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

久々に踏んだRubyの罠

2
Posted at

以下のコードが、なぜこの出力になるのか十数分悩みました(説明用に改変しています)。

h = {'code' => "A", 'value' => 1}

code = h["code"],
value = h["value"]

p code

# なぜか出力がこうなる
#
# ["A", 1]

種明かし

codeへの代入文の末尾にカンマがあります。これが原因です。

Rubyは文法の自由度が高い言語です。代入式を他の式で使用することができるし、式の途中で改行したり、カッコを省略したり改行を入れたりできる。

code = h["code"],
value = h["value"]

このように解釈される↓

code = h["code"], value = h["value"]

さらにカッコを補うとこうなる↓

code = [h["code"], (value = h["value"])]

(※Rubyインタープリターの厳密な動作の説明ではありません。)

と、いうわけで、code には配列が代入されてしまいます。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?