Flowdock
method

first

Importance_3
Ruby on Rails latest stable (v4.0.2) - 4 notes - Class: ActiveSupport::CoreExtensions::String::Access

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v2.3.8) is shown here.

These similar methods exist in v4.0.2:

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"
Show source
Register or log in to add new notes.
February 26, 2009 - (v1.0.0 - v2.1.0)
0 thanks

Conflicts with Ruby 1.8.7

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 to instead of String.first

March 12, 2009
0 thanks

PS

That didn’t render properly. Use:

String[1..1]

instead of

String.first
March 12, 2009 - (<= v2.1.0)
0 thanks

Another fix

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
April 1, 2009
0 thanks

Conflicts with 1.8.7 (and 1.9.1)

“abc”.to(0) fails in 1.8.7 and “String” should be “String” (or “abc”). Using to_a breaks in 1.9.1.

I’m using “abc”. :(