camelcaseとsnakecaseの変換

いろいろ丁寧に変換するようにした

--to_snake
'ShoHashimoto' => 'sho_hashimoto'
'sho_hashimoto' => 'sho_hashimoto'
'shokai' => 'shokai'
'SHOKAI' => 'shokai'
'This is a  pen' => 'this_is_a_pen'
'EventMachine::HTTPRequest' => 'event_machine_httprequest'
'tEst' => 't_est'
--to_camel
'ShoHashimoto' => 'ShoHashimoto'
'sho_hashimoto' => 'ShoHashimoto'
'shokai' => 'Shokai'
'SHOKAI' => 'SHOKAI'
'This is a  pen' => 'ThisIsAPen'
'EventMachine::HTTPRequest' => 'EventMachine::HTTPRequest'
'tEst' => 'TEst'
#!/usr/bin/env ruby

class String
  def to_snake
    ptn = /[A-Z\s]*[^A-Z]*/
    self =~ ptn ? self.scan(ptn).map{|i|
      i.gsub(/[\s:]+/,'_').downcase
    }.join('_').gsub(/__+/,'_').sub(/_$/,'') : self
  end
  def to_camel
    self.split(/[_\s]+/).map{|i|
      a,b,c = i.split(/^(.)/)
      "#{b.upcase}#{c}"
    }.join('')
  end
end

# puts 'ShoHashimoto'.to_snake
# puts 'sho_hashimoto'.to_camel

[:to_snake, :to_camel].each do |mes|
  puts "--#{mes}"
  ['ShoHashimoto', 'sho_hashimoto', 'shokai', 'SHOKAI',
   'This is a  pen', 'EventMachine::HTTPRequest', 'tEst'].each do |s|
    puts "'#{s}' => '#{s.method(mes).call}'"
  end
end