Last active
December 18, 2020 16:46
-
-
Save ekdevdes/2450285 to your computer and use it in GitHub Desktop.
Ruby: Humanize a string (the first "real" ruby method I've ever written. It was approximately 2 years ago)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# words must be seperated by an underscore | |
# ex. "hello_there-pal" isnt valid but "hello_there_pal" is | |
# humanize "hello_there" # => "Hello There" | |
# humanize "hello there" # => "Hello There" | |
# humanize "hello_there", {format: :class,without: :dashes, separator: :space} | |
# options | |
# format: | |
# :class -> change a string like "hello string" to "HelloString" | |
# :sentence -> change a string like "hello_String" to "Hello string" | |
# :allcaps -> changes a string like "hello_string" to "Hello_String" | |
# :nocaps -> changes a string like "hello_string" to "hello string" | |
def humanize (value, options = {}) | |
if options.empty? | |
options[:format] = :sentence | |
end | |
values = [] | |
if value.include? '_' | |
values = value.split('_') | |
values.each { |v| v.downcase! } | |
if options[:format] == :allcaps | |
values.each do |value| | |
value.capitalize! | |
end | |
if options.empty? | |
options[:seperator] = " " | |
end | |
return values.join " " | |
end | |
if options[:format] == :class | |
values.each do |value| | |
value.capitalize! | |
end | |
return values.join "" | |
end | |
if options[:format] == :sentence | |
values[0].capitalize! | |
return values.join " " | |
end | |
if options[:format] == :nocaps | |
return values.join " " | |
end | |
end | |
end | |
puts humanize "hello_there", format: :class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
values.each { |v| v.downcase! }
can be to this furthervalues.each(&:downcase!)