Skip to content

Instantly share code, notes, and snippets.

@ekdevdes
Last active December 18, 2020 16:46
Show Gist options
  • Save ekdevdes/2450285 to your computer and use it in GitHub Desktop.
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)
# 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
@ekdevdes
Copy link
Author

I know rails has something like this but, like the title says this is my first real ruby method and I wanted to test out my skills. What do you guys think?

@whatsthebeef
Copy link

You could change this part (and likewise with the other each loops to reduce bulk)

values.each_index do |index|  
   # lower case each item in array
   values[index].downcase!
end

To this

values.each { |v| v.downcase! }  

Also you can improve the formatting quite a lot.

@bibinvenugopal
Copy link

values.each { |v| v.downcase! } can be to this further values.each(&:downcase!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment