Ruby on Rails: Array method From

Looking at RoR 5.0 beta’s source code, here’s a very simple method that has been around for a while and does what the framework is so great at: humanizing the programming interface.

/activesupport/lib/active_support/core_ext/array/access.rb@from

 # Returns the tail of the array from +position+.
 #
 # %w( a b c d ).from(0) # => ["a", "b", "c", "d"]
 # %w( a b c d ).from(2) # => ["c", "d"]
 # %w( a b c d ).from(10) # => []
 # %w().from(0) # => []
 # %w( a b c d ).from(-2) # => ["c", "d"]
 # %w( a b c ).from(-10) # => []
 def from(position)
   self[position, length] || []
 end

It’s an array method, so it will use the dot-chained array as self as is the case in Ruby.

It uses the already pretty convenient array[new_start, new_end] notation to chop off the beginning of the array.

If you are working on an array that has, say, 5 elements, but passed it a position value of 8, the above operation will mercifully not throw an exception – rather, it will just return nil.

In those cases the || [] ensures the method will still return an array type, in this case an empty one, which is a sweet spot between making sense and being convenient.