first(limit = 1)
public

Returns the first character of the string or the first limit characters.

Examples:

  "hello".first     # => "h"
  "hello".first(2)  # => "he"
  "hello".first(10) # => "hello"

4Notes

Conflicts with Ruby 1.8.7

insane-dreamer · Feb 26, 2009

Using this with Rails < 2.2.x and Ruby 1.8.7 will create a conflict between ActiveSupport and Ruby, generating the following error:

>> '/'.first
NoMethodError: undefined method `[]' for #<Enumerable::Enumerator:0x176b974>
from /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/core_ext/string/access.rb:43:in `first'

So if using an older version of Rails with Ruby 1.8.7, use String[1..1] to instead of String.first

PS

insane-dreamer · Mar 12, 2009

That didn't render properly. Use:

String[1..1]

instead of

String.first

Another fix

insane-dreamer · Mar 12, 2009

Another way around this problem, with code that already employs String.first, is to change the ActiveSupport definition as follows (in environment.rb)

module ActiveSupport
module CoreExtensions 
  module String 
    module Access
      def first(limit = 1)
        chars.to_a[0..(limit - 1)].to_s
      end
    end
  end
end
end

Conflicts with 1.8.7 (and 1.9.1)

dvdplm · Apr 1, 2009

"abc".to(0) fails in 1.8.7 and "String"[1..1] should be "String"[0..0] (or "abc"[0...1]). Using to_a breaks in 1.9.1.

I'm using "abc"[0..0]. :(