Class: String

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

Overview

Core string extensions

Instance Method Summary collapse

Instance Method Details

#camelizeObject Also known as: classify

Camelize a string

Examples:

Camelize a string

"hello_world".camelize # => HelloWorld


9
10
11
# File 'lib/ext/string.rb', line 9

def camelize
  split('_').collect(&:capitalize).join
end

#constantizeObject

Look up a constant via a string.

rubocop:disable LineLength

Examples:

Using constantize

"Object".constantize # => Object


31
32
33
34
35
36
37
38
39
# File 'lib/ext/string.rb', line 31

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"


18
19
20
21
22
23
24
# File 'lib/ext/string.rb', line 18

def underscore
  gsub(/::/, '/')
    .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
    .gsub(/([a-z\d])([A-Z])/, '\1_\2')
    .tr('-', '_')
    .downcase
end