Ruby Koans reveals unexpected behavior in Ruby. Some quirks include..

1. Array Slicing

1
2
3
4
5
array = [:peanut, :butter, :and, :jelly]
array[4]   # => nil .. Ok
array[4,0] # => []  .. Ok
array[5]   # => nil .. Ok
array[5,0] # => nil .. Wait. What? 

SO explains that array[4,0] leaves room for assignment. This makes sense until..

1
2
3
4
5
# continued from above 
array[7] = :bread
array        # => [:peanut, :butter, :and, :jelly, nil, nil, nil, :bread]
array[4,0]   # => []
array[5,0]   # => []

Slots can be skipped. Which means that # => [] is not a prerequisite for assignment.

The behavior seems inconsistent. Explanations are welcomed.

2. Default Hashes

This behavior makes sense in hindsight although it can be initially confusing.

Comments