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 !
danielharan
September 22, 2008, September 22, 2008 16:12, permalink
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"
Tj Holowaychuk
September 22, 2008, September 22, 2008 17:06, permalink
Ah good point, that seems cleaner :)
Adam
September 23, 2008, September 23, 2008 03:31, permalink
ActiveSupport already does this.
1 2 3 4
require "activesupport" # >> "hello_world".camelize(:lower) # => "helloWorld"
Adam
September 23, 2008, September 23, 2008 14:33, permalink
That does not prevent you from using ActiveSupport. It's a Ruby library like any other.
Christian Romney
September 30, 2008, September 30, 2008 14:21, permalink
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.
Tj Holowaychuk
September 30, 2008, September 30, 2008 15:11, permalink
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
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?