Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/ext/string.rb

Overview

Core string extensions

Instance Method Summary collapse

Instance Method Details

#constantizeObject

Look up a constant via a string.

rubocop:disable LineLength

Examples:

Using constantize

"Object".constantize # => Object


22
23
24
25
26
27
28
29
30
# 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

#underscoreObject Also known as: snakecase

Underscore a String. This method will also downcase the string

Examples:

Underscore a string

"HelloWorld" # => "hello_world"


9
10
11
12
13
14
15
# 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