Remove First and Last Character (8kyu) [Ruby]
Chek kata on Codewars
It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.
Let's start with a naive solution. Solving with
def remove_char(s) new_s = '' i = 1 while i < s.length - 1 new_s += s[i] i += 1 end new_s end
A more efficient solution will be to use
def remove_char(s) s[1...-1] end
Or if don't like so many dots 😅
def remove_char(s) s[1..-2] end
Not the most efficient solution. But we can convert a string to an array and use array methods.
def remove_char(s) new_s = s.split('') new_s.pop new_s.shift new_s.join end
Also, we can use a regular expression here with the replace method.
def remove_char(s) s.gsub(/^\w|\w\b/, "") end