class String

Core string extensions

Public Instance Methods

constantize() click to toggle source

Look up a constant via a string.

@example Using constantize

"Object".constantize # => Object

rubocop:disable LineLength

# File lib/ext/string.rb, line 22
def constantize
  names = split('::')
  names.shift if names.empty? || names.first.empty?
  constant = Object
  names.each do |name|
    constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
  end
  constant
end
snakecase()
Alias for: underscore
underscore() click to toggle source

Underscore a String. This method will also downcase the string

@example Underscore a string

"HelloWorld" # => "hello_world"
# File lib/ext/string.rb, line 9
def underscore
  gsub(/::/, '/')
    .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
    .gsub(/([a-z\d])([A-Z])/, '\1_\2')
    .tr('-', '_')
    .downcase
end
Also aliased as: snakecase