Class: String

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

Overview

Adds some needed methods to String objects

Author

Michael Heijmans ([email protected])

Copyright

Copyright © 2013-2015 Michael Heijmans

License

MIT

Instance Method Summary collapse

Instance Method Details

#camelizeObject

CamelCase's the string

Examples:

camelize “hello_world”

"hello_world".camelize #=> "HelloWorld"

25
26
27
28
29
30
31
# File 'lib/string-mixins.rb', line 25

def camelize
  a = self.split("_")
  a.each do |b|
    b.capitalize_first_letter!
  end
  return a.join("")
end

#capitalize_first_letterObject

Capitalizes the first letter of the string and returns a new string


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

def capitalize_first_letter
    self[0].chr.capitalize + self[1, size]
end

#capitalize_first_letter!Object

Capitalizes the first letter of the string in place


14
15
16
17
18
19
# File 'lib/string-mixins.rb', line 14

def capitalize_first_letter!
  unless self[0] == (c = self[0,1].upcase[0])
    self[0] = c
    self
  end
end

#classifyObject

Casts the string into its class constant

Examples:

classify “Bender” into Bender

"Bender".classify #=> Bender

37
38
39
# File 'lib/string-mixins.rb', line 37

def classify
  return eval(self)
end

#to_boolObject

Casts boolean looking string into a Boolean object

Examples:

“true” to TrueClass

"true".to_bool #=> true

45
46
47
48
49
50
51
52
53
54
# File 'lib/string-mixins.rb', line 45

def to_bool
  case self
  when /^true$|^t$|^yes$|^y$|^1$/i
    return true
  when /^false$|^f$|^no$|^n$|^0$/i
    return false
  else
    raise TypeError, "'#{self}' can not be cast into a boolean"
  end
end