Home > katas > Remove First and Last Character (8kyu) [Ruby]
Remove First and Last Character (8kyu) [Ruby]
Chek kata on Codewars
Description:
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.
Solution 1.1
Let's start with a naive solution. Solving with loop
.
def remove_char(s)
new_s = ''
i = 1
while i < s.length - 1
new_s += s[i]
i += 1
end
new_s
end
Solution 2.1
A more efficient solution will be to use slice
method.
def remove_char(s)
s[1...-1]
end
Solution 2.2
Or if don't like so many dots 😅
def remove_char(s)
s[1..-2]
end
Solution 3.1
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
Solution 4.1
Also, we can use a regular expression here with the replace method.
def remove_char(s)
s.gsub(/^\w|\w\b/, "")
end