When you use a word that consists of multiple words in an identifier, you cannot include spaces, so you must somehow represent a word break. For example, the following notation is used.
ActiveSupport provides a set of useful methods for converting between these.
You can use String # underscore
to convert CamelCase to snake_case.
You can use String # camelize
to convert snake_case to UpperCamelCase [^ lcc].
[^ lcc]: Use camelize (: lower)
to convert to lowerCamelCase.
As below:
require "active_support/inflector"
p "BookTitle".underscore # => "book_title"
p "book_title".camelize # => "BookTitle"
Looking at this, ʻunderscore and
camelize` are inverse transformations of each other.
require "active_support/inflector"
p "BookTitle".underscore.camelize # => "BookTitle"
p "book_title".camelize.underscore # => "book_title"
It seems (always) to return to the original when both are overlapped like.
However, in some cases this is not the case. that is
require "active_support/inflector"
p "OfficialURL".underscore # => "official_url"
p "CSVFile".underscore # => "csv_file"
This is a case that contains words that consist only of uppercase letters, such as ʻURLand
CSV. The ʻunderscore
method splits CSVFile
into CSV
and File
into a snake_case, as humans would expect.
However, this loses the information that the converted ʻurland
csv were originally spelled in uppercase only, so
camelize` them will not restore them.
require "active_support/inflector"
p "OfficialURL".underscore.camelize # => "OfficialUrl"
p "CSVFile".underscore.camelize # => "CsvFile"
It was an example that a convenient method could fall into a pitfall if the specifications are not well understood and used. (Someday, I was addicted to [^ ot], actually!)
[^ ot]: Initially, it was made into a snake_case with a code like gsub (/. (? = [AZ]) /) {$ & +" _ "} .downcase
, and later the processing using ActiveSupport was mixed. Sometimes something went wrong.
Recommended Posts