Skip to content

Commit

Permalink
Clearer String#first and #last edge cases. Fix that foo.first(0) == i…
Browse files Browse the repository at this point in the history
…nstead of foo.
  • Loading branch information
jeremy committed Apr 17, 2009
1 parent abb899c commit 60896ca
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
18 changes: 15 additions & 3 deletions activesupport/lib/active_support/core_ext/string/access.rb
Expand Up @@ -41,17 +41,29 @@ def to(position)
# "hello".first(2) # => "he"
# "hello".first(10) # => "hello"
def first(limit = 1)
mb_chars[0..(limit - 1)].to_s
if limit == 0
''
elsif limit >= size
self
else
mb_chars[0...limit].to_s
end
end

# Returns the last character of the string or the last +limit+ characters.
#
# Examples:
# "hello".last # => "o"
# "hello".last(2) # => "lo"
# "hello".last(10) # => "hello"
def last(limit = 1)
(mb_chars[(-limit)..-1] || self).to_s
if limit == 0
''
elsif limit >= size
self
else
mb_chars[(-limit)..-1].to_s
end
end
end
else
Expand Down
2 changes: 2 additions & 0 deletions activesupport/test/core_ext/string_ext_test.rb
Expand Up @@ -132,10 +132,12 @@ def test_access

assert_equal "h", s.first
assert_equal "he", s.first(2)
assert_equal "", s.first(0)

assert_equal "o", s.last
assert_equal "llo", s.last(3)
assert_equal "hello", s.last(10)
assert_equal "", s.last(0)

assert_equal 'x', 'x'.first
assert_equal 'x', 'x'.first(4)
Expand Down

0 comments on commit 60896ca

Please sign in to comment.