Crystal: String#camelcase does not correctly handle SHOUT_CASE

Created on 13 Aug 2020  路  4Comments  路  Source: crystal-lang/crystal

Steps to Reproduce

puts "SHOUT_CASE".camelcase

Expected Result

ShoutCase

Actual Result

SHOUTCASE
feature discussion topictext

Most helpful comment

These are really just convenience methods and most use cases are not performance bound. So I don't think we should add more implementations to stdlib. Composition is usually fine.
If performance is a concern, you can roll your own. Or maybe create a shard for more specific (and performant) string operations.

All 4 comments

Kind of related to #9411. One could make the argument that there's no shorthand method to produce SHOUT_CASE from any input, so it's just not within the realm of the standard library to handle it. Put differently, producing SHOUT_CASE means two operations, .underscore.upcase, so why not require the inverse to go back, .downcase.camelcase?

I'd prefer a more efficient algorithm. Capitalize or leave-capitalized any character following a _, that isn't the first non-_ character, lower-case the rest of the non-_ characters.

If you're concerned about performance, it's trivial to roll your own:

String.build do |io|
  prev = nil
  input.each_char do |char|
    next prev = char if char == '_'
    io << (prev.nil? || prev == '_' ? char.upcase : char.downcase)
    prev = char
  end
end

These are really just convenience methods and most use cases are not performance bound. So I don't think we should add more implementations to stdlib. Composition is usually fine.
If performance is a concern, you can roll your own. Or maybe create a shard for more specific (and performant) string operations.

Was this page helpful?
0 / 5 - 0 ratings