dax
dax

Reputation: 11017

What's happening with array.last[x]?

I came across this:

a = [1, 2, 3, 4, 5, 6, 7]
a.last # => 7
a.last[-1] # => 0
a.last[0] # => 1
a.last[1] # => 1 
a.last[100] # => 0

Can someone explain what's happening and why?

Upvotes: 0

Views: 54

Answers (2)

Stefan
Stefan

Reputation: 114258

Array#last returns the last element, i.e. 7. Appending [] simply calls Fixnum#[], returning the number's nth bit:

7[0]   # => 1
7[1]   # => 1 
7[2]   # => 1 
7[3]   # => 0
# ... 
7[100] # => 0

7.to_s(2) #=> "111"

Upvotes: 2

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71019

You are taking the n-th bit of a number using the operator [] on a Fixnum. Thus you are first taking the last value in the array and then you are listing its bits. Negative index bits are always 0.

Upvotes: 1

Related Questions