title: Ruby convention for accessing first/last element in array
body: <p>This is a question about conventions. The two sets of commands below return identical results.</p>
  
  <pre><code>a = [1, 2, 3]
  
  a.first  # =&gt; 1
  a[0]     # =&gt; 1
  
  a.last   # =&gt; 3
  a[-1]    # =&gt; 3
  </code></pre>
  
  <p>Which of these is preferred in Ruby, the explicit index or the functions? Assuming, of course, that this is in code which <em>always</em> accesses the first or last element.</p>
  
  <p>Note: I've been thinking about the cycles each would take. Because <code>first</code> and <code>last</code> accept parameters, they will have a little more overhead, but I don't know if that affects what the community prefers.</p>
  
  <p>Thanks!</p>
  
  <hr>
  
  <p><strong>EDIT</strong></p>
  
  <p>If you read the comments on this post, there was a big debate about my last paragraph. While I failed to remember that <code>[x]</code> is equivalent to <code>.[](x)</code>, I was correct in my conclusion that first and last have a bit more overhead. Considering the nature of both, I believe that this is due to the argument check for <code>first</code>/<code>last</code>. These need to check if there are arguments whereas <code>[]</code> can assume that they exist.</p>
  
  <p><strong>CODE</strong></p>
  
  <pre><code>require 'benchmark'
  
  a = [1..1000]
  
  MAX = 1000000
  
  Benchmark.bm(15) do |b|
    b.report("small first") { MAX.times do; a.first; end }
    b.report("small [0]")   { MAX.times do; a[0];    end }
    b.report("small last")  { MAX.times do; a.last;  end }
    b.report("small [-1]")  { MAX.times do; a[-1];   end }
  end
  
  a = [1..100000000000]
  
  Benchmark.bm(15) do |b|
    b.report("large first") { MAX.times do; a.first; end }
    b.report("large [0]")   { MAX.times do; a[0];    end }
    b.report("large last")  { MAX.times do; a.last;  end }
    b.report("large [-1]")  { MAX.times do; a[-1];   end }
  end
  </code></pre>
  
  <p><strong>RESULTS</strong></p>
  
  <pre><code>                      user     system      total        real
  small first       0.350000   0.000000   0.350000 (  0.901497)
  small [0]         0.330000   0.010000   0.340000 (  0.857786)
  small last        0.370000   0.000000   0.370000 (  1.054216)
  small [-1]        0.370000   0.000000   0.370000 (  1.137655)
                        user     system      total        real
  large first       0.340000   0.010000   0.350000 (  0.897581)
  large [0]         0.320000   0.010000   0.330000 (  0.889725)
  large last        0.350000   0.000000   0.350000 (  1.071135)
  large [-1]        0.380000   0.000000   0.380000 (  1.119587)
  </code></pre>