Permalink
Browse files

Add rindex to ActiveSupport::Multibyte::Chars.

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information...
1 parent e06a0b0 commit 4dda9b644df5e4386f693a4b7bd00fe787f41a28 @eostrom eostrom committed with jeremy Aug 10, 2009
Showing with 20 additions and 0 deletions.
  1. +13 −0 activesupport/lib/active_support/multibyte/chars.rb
  2. +7 −0 activesupport/test/multibyte_chars_test.rb
@@ -210,6 +210,19 @@ def index(needle, offset=0)
index ? (self.class.u_unpack(@wrapped_string.slice(0...index)).size) : nil
end
+ # Returns the position _needle_ in the string, counting in
+ # codepoints, searching backward from _offset_ or the end of the
+ # string. Returns +nil+ if _needle_ isn't found.
+ #
+ # Example:
+ # 'Café périferôl'.mb_chars.rindex('é') #=> 5
+ # 'Café périferôl'.mb_chars.rindex(/\w/u) #=> 13
+ def rindex(needle, offset=nil)
+ offset ||= length
+ index = @wrapped_string.rindex(needle, offset)
+ index ? (self.class.u_unpack(@wrapped_string.slice(0...index)).size) : nil
+ end
+
# Like <tt>String#[]=</tt>, except instead of byte offsets you specify character offsets.
#
# Example:
@@ -234,6 +234,13 @@ def test_index_should_return_character_offset
assert_equal 3, @chars.index('')
end
+ def test_rindex_should_return_character_offset
+ assert_nil @chars.rindex('u')
+ assert_equal 1, @chars.rindex('')
+ assert_equal 6, 'Café périferôl'.mb_chars.rindex('é')
+ assert_equal 12, 'Café périferôl'.mb_chars.rindex(/\w/u)
+ end
+
def test_indexed_insert_should_take_character_offsets
@chars[2] = 'a'
assert_equal 'こにaわ', @chars

0 comments on commit 4dda9b6

Please sign in to comment.