1

I'm working on an exercise from Codewars. The exercise is to convert a string into camel case. For example, if I had

the-stealth-warrior

I need to convert it to

theStealthWarrior

Here is my code

def to_camel_case(str)
  words = str.split('-')
  a = words.first
  b = words[1..words.length - 1].map{|x|x.capitalize}
  new_array = []
  new_array << a << b
  return new_array.flatten.join('')
end

I just tested it out in IRB and it works, but in codewars, it won't let me pass. I get this error message.

NoMethodError: undefined method 'map' for nil:NilClass

I don't understand this, my method was definitely right.

5 Answers5

0

You need to think about edge cases. In particular in this situation if the input was an empty string, then words would be [], and so words[1..words.length - 1] would be nil.

Codewars is probably testing your code with a range of inputs, including the emplty string (and likely other odd cases).

matt
  • 78,533
  • 8
  • 163
  • 197
0

The following works in Ruby 2 for me, even if there's only one word in the input string:

def to_camel_case(str)
   str.split('-').map.with_index{|x,i| i > 0 ? x.capitalize : x}.join
end

to_camel_case("the-stealth-warrior")   # => "theStealthWarrior"
to_camel_case("warrior")   # => "warrior"

I know .with_index exists in 1.9.3, but I can't promise it will work with earlier versions of Ruby.

pjs
  • 18,696
  • 4
  • 27
  • 56
0

A simpler way to change the text is :

irb(main):022:0> 'the-stealth-warrior'.gsub('-', '_').camelize
 => "TheStealthWarrior"
mmsilviu
  • 1,211
  • 15
  • 25
0

This should do the trick:

 str.gsub("_","-").split('-').map.with_index{|x,i| i > 0 ? x.capitalize : x}.join

It accounts for words with underscores

Redbeard
  • 115
  • 6
-1

Maybe there's a test case with only one word?

In that case, you'd be trying to do a map on words[1..0], which is nil.

Add logic to handle that case and you should be fine.

Grondag
  • 102
  • 2