24
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rubyでsnake_caseをCamelCaseへ変換する

Last updated at Posted at 2015-09-13

コード生成とかしてる時に _ で要素を繋いだ snake_case から、大文字小文字の組み合わせで単語の繋ぎ目を表現する CamelCase へ変換する必要に駆られる事があります。
Rails使ってればActiveRecordがなんとかしてくれるのですが、RailsばかりがRubyではありません。

書けば済む話ですが、ググってもそのものズバリのスニペットが見当たらなかったのでおいておきます。

class String
  def to_camel()
    self.split("_").map{|w| w[0] = w[0].upcase; w}.join
  end
end

こう書いておくと

"snake_case".to_camel # => SnakeCase

こうなります。

ちなみに逆方向は

class String
  def to_snake()
    self
      .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
      .gsub(/([a-z\d])([A-Z])/, '\1_\2')
      .tr("-", "_")
      .downcase
  end
end

こんな感じに書くらしいです。
参考URL: Converting camel case to underscore case in ruby

24
18
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?