F1e3ab214a976a39cfd713bc93deb10f

I am pretty new to Ruby (one day), however this works fine, but I would like to allow the first character to be lower case optionally, anyone have a smaller solution for this?

1
2
3
4
5
6
7
  
  #
  # Convert a string to CamelCase.
  #
  def camelize
    self.split(/[^a-z0-9]/i).map{|w| w.capitalize}.join
  end

Refactorings

No refactoring yet !

880cbab435f00197613c9cc2065b4f5a

danielharan

September 22, 2008, September 22, 2008 16:12, permalink

2 ratings. Login to rate!

Rather than pass a flag and mix concerns, how about chaining?

1
2
3
4
5
6
7
8
9
10
class String
  def uncapitalize
    self.sub(/(^.)/) {|m| m.downcase }
  end
end

>> "hello_world".camelize
=> "HelloWorld"
>> "hello_world".camelize.uncapitalize
=> "helloWorld"
F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

September 22, 2008, September 22, 2008 17:06, permalink

No rating. Login to rate!

Ah good point, that seems cleaner :)

A8d3f35baafdaea851914b17dae9e1fc

Adam

September 23, 2008, September 23, 2008 03:31, permalink

3 ratings. Login to rate!

ActiveSupport already does this.

1
2
3
4
require "activesupport"

# >> "hello_world".camelize(:lower)
# => "helloWorld"
F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

September 23, 2008, September 23, 2008 14:18, permalink

No rating. Login to rate!

I am not using rails

A8d3f35baafdaea851914b17dae9e1fc

Adam

September 23, 2008, September 23, 2008 14:33, permalink

No rating. Login to rate!

That does not prevent you from using ActiveSupport. It's a Ruby library like any other.

4d4539a5c326b9fc26e8b1fa1a850df1

Christian Romney

September 30, 2008, September 30, 2008 14:21, permalink

No rating. Login to rate!

I definitely agree with Adam's insight: don't reinvent the wheel. Try having a look at Ruby Facets. It's got tons of well-organized utility methods, and you can require as much or as little code as you need.

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

September 30, 2008, September 30, 2008 15:11, permalink

No rating. Login to rate!

Just learning :) thanks guys! I have a stupid question that I cannot seem to find documentation on. When your creating a gem and your executable in the bin directory requires its own library it should use require just like a regular library would right? not hacking in some path for Ruby to search or anything. Even when my gem is built / installed the exec is still not available.. frustrating the rest seems so straight forward

Your refactoring





Format Copy from initial code

or Cancel