Converting string from snake_case to CamelCase in Ruby
If you're using Rails, String#camelize is what you're looking for.
"active_record".camelize # => "ActiveRecord"
"active_record".camelize(:lower) # => "activeRecord"
If you want to get an actual class, you should use String#constantize on top of that.
"app_user".camelize.constantize
Converting camel case to underscore case in ruby
Rails' ActiveSupport
adds underscore to the String using the following:
class String
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
Then you can do fun stuff:
"CamelCase".underscore
=> "camel_case"
Converting snake case to normal sentence in Ruby
humanize is your thing:
[4] pry(main)> "hello_world".humanize
"Hello world"
Julia implementation for converting string to snake_case/CamelCase
This doesn't use "reserved words" as mentioned in the question, but instead assumes that a series of upper case letters (along with preceding numbers if any, for eg. "30MW") is supposed to be a word of its own; while also ensuring that "Price" in "30MWPrice" is seen as a separate word.
function snake_case(camelstring::S) where S<:AbstractString
wordpat = r"
^[a-z]+ | #match initial lower case part
[A-Z][a-z]+ | #match Words Like This
\d*([A-Z](?=[A-Z]|$))+ | #match ABBREV 30MW
\d+ #match 1234 (numbers without units)
"x
smartlower(word) = any(islowercase, word) ? lowercase(word) : word
words = [smartlower(m.match) for m in eachmatch(wordpat, camelstring)]
join(words, "_")
end
using Test
function runtests()
@test snake_case("askBest30MWPrice") == "ask_best_30MW_price"
@test snake_case("welcomeToAIOverlords") == "welcome_to_AI_overlords"
@test snake_case("queryInterface") == "query_interface"
@test snake_case("tst") == "tst"
@test snake_case("1234") == "1234"
@test snake_case("column12Value") == "column_12_value"
@test snake_case("readTOC") == "read_TOC"
end
(Probably Unimportant) Side Note: You can replace [a-z]
with [[:lower:]]
and [A-Z]
with [[:upper:]]
above to make it work for some more languages, for eg. snake_case("helloΩorld")
will then return "hello_ωorld"
. However (like with anything Unicode), there are nuances - for eg., my language (Tamil) doesn't have letter cases, so its letters fall outside both [:lower:]
and [:upper:]
.
A proper Unicode solution using \p{Lo}
, [:digit:]
, and whatever else, is left as an exercise to the reader.
How to convert snake case to dash case in Rails
dasherize
right there on the same page
"hello_world".dasherize # => 'hello-world'
Converting nested hash keys from CamelCase to snake_case in Ruby
You need to treat Array and Hash separately. And, if you're in Rails, you can use underscore
instead of your homebrew to_snake_case
. First a little helper to reduce the noise:
def underscore_key(k)
k.to_s.underscore.to_sym
# Or, if you're not in Rails:
# to_snake_case(k.to_s).to_sym
end
If your Hashes will have keys that aren't Symbols or Strings then you can modify underscore_key
appropriately.
If you have an Array, then you just want to recursively apply convert_hash_keys
to each element of the Array; if you have a Hash, you want to fix the keys with underscore_key
and apply convert_hash_keys
to each of the values; if you have something else then you want to pass it through untouched:
def convert_hash_keys(value)
case value
when Array
value.map { |v| convert_hash_keys(v) }
# or `value.map(&method(:convert_hash_keys))`
when Hash
Hash[value.map { |k, v| [underscore_key(k), convert_hash_keys(v)] }]
else
value
end
end
Related Topics
Why Can't I Install Rails on Lion Using Rvm
No Such File to Load - Readline
Why Does Ruby'S 'Gets' Includes the Closing Newline
What Does Class_Eval ≪≪-"End_Eval", _File_, _Line_ Mean in Ruby
Rails Each Loop Insert Tag Every 6 Items
How to Sort an Array in Ruby to a Particular Order
Shortcut to Make Case/Switch Return a Value
How to Prompt for a Sudo Password Using Ruby
Setting Up Rake-Pipeline for Use with Handlebars Alongside Google App Engine
Extract Single String from HTML Using Ruby/Mechanize (And Nokogiri)
How to Access Method Arguments in Ruby
Difference Between Ruby and Ruby on Rails
Why Are Symbols in Ruby Not Thought of as a Type of Variable
Converting String from Snake_Case to Camelcase in Ruby
Fibonacci Sequence in Ruby (Recursion)
"Gem Install Rails" Fails With Dns Error