为什么 3[0] 和 3[1] 在 Ruby 中的结果是 1?

Why 3[0] and 3[1] results in 1 in Ruby?

整数可以像数组一样访问索引,这很有趣。

所以我们可以做这样的事情:

puts 3[0] returns 1.

puts 3[1] returns 1.

puts 3[2] returns 0.

这是怎么回事?

您正在访问 int 的位!查看 this 文档了解更多详情。

the docsInteger#[]:

Bit Reference---Returns the nth bit in the binary representation of int, where int[0] is the least significant bit.

3 在二进制中是 11,所以 3[0](最不重要的一个)和 3[1]1,其他都是 0.