ruby - Why do I keep getting an undefined method error? -


i'm trying reverses string:

def reverse(string)   reversed_string = ""   string.split("")    string.each |letter, idx|     reversed_string = string.length > 0 ? letter[idx] + reversed_string : reversed_string   end end  reverse("abc") 

i keep getting error 'split' method not exist 'each' method.

there lot of ways you're going:

def reverse(s)   ary = s.split('') # => ["f", "o", "o"], ["b", "a", "r"]   reversed_str = ''   ary.size.times     reversed_str << ary.pop # => "o", "oo", "oof", "r", "ra", "rab"   end   reversed_str # => "oof", "rab" end  reverse('foo') # => "oof" reverse('bar') # => "rab" 

this isn't fastest, and, if you're trying learn how replace method, reverse, should try writing several different variants, run benchmarks you've discovered your fastest way of doing it. here's how ruby defines string.reverse.

also note reversing string not same reversing array. they're similar, that'd second lesson you.


Comments