File: camel_case.rb

package info (click to toggle)
libextlib-ruby 0.9.13-2%2Bdeb6u1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze-lts
  • size: 532 kB
  • ctags: 487
  • sloc: ruby: 7,118; makefile: 3
file content (45 lines) | stat: -rw-r--r-- 1,107 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env ruby
require "rubygems"
require "rbench"

require "pathname"

class String
  ##
  # @return <String> The string converted to camel case.
  #
  # @example
  #   "foo_bar".camel_case #=> "FooBar"
  def camel_case
    return self if self !~ /_/ && self =~ /[A-Z]+.*/
    split('_').map{|e| e.capitalize}.join
  end

  # By default, camelize converts strings to UpperCamelCase.
  #
  # camelize will also convert '/' to '::' which is useful for converting paths to namespaces
  #
  # @example
  #   "active_record".camelize #=> "ActiveRecord"
  #   "active_record/errors".camelize #=> "ActiveRecord::Errors"
  #
  def camelize
    self.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase }
  end
end # class String



# It's not really fair to compare the two but
# Extlib has no direct equivalent to String#camel_case.
RBench.run(10_000) do
  report "String#camelize" do
    "underscore_string".camelize
    "a_bit_longer_underscore_string".camelize
  end

  report "String#camel_case" do
    "underscore_string".camel_case
    "a_bit_longer_underscore_string".camel_case
  end
end