WARMUP: Reverse a string without built-in methods (Ruby/JS solutions)
Warming up is a good thing. Here's a basic one to start with.
Write a method/function that reverses a string (w/out a built in ".reverse" method/function)
ex. input "warmup" should return the string "pumraw"
Ruby solution
def reverse_string(str)
reversed_string = ""
letter_index = str.length - 1
(str.length).times do
reversed_string << str[letter_index]
letter_index-= 1
end
reversed_string
end
There might be more efficient solutions, feel free to yell at me. How it works, line-by-line:
- Define a method
reverse_string
which takes in a string as an argument - On the first line of the method body, define a new, empty string (
reversed_string
) which will eventually hold the reversed string - Then we define a variable
letter_index
and set equal to the length of the input string - 1. In programming, data is typically zero-indexed. Meaning the first element in a string, array, etc. is accessed at index[0]. In the string "warmup" the first character "w" is index[0], and the final character "p" is index[5] (you can also access the last character at index[-1] where useful). We initially set theletter_index
tostr.length - 1
so that we can access the LAST character in the input string, no matter how long the string is. This will make more sense as we move along. - Initiate a do-loop. Note that in Ruby, we can use the
x.times do {}
loop, which executes a code block a specific number of times. As far as I know this specific loop syntax is unique to ruby. In our case, we know we want to perform the code block as many times as there are letters in the original input string. - On the first line of the do-loop block, we shovel the last letter of the original input string (
str
) into the newreversed_string
using the<<
shovel operator. Using the shovel operator, the value on the right-side of the operator (string[letter_index]
) will be added onto the end of the value on the left-side (reversed_string
). So in the first loop (using the input string "warmup" as an example), we add the letter "p" to the end of the currentreversed_string
. - On the second line of the do-loop block, we use the
-=
operator to subtract 1 from the current value ofletter_index
. Using the-=
operator is equivalent shorthand to writingletter_index = letter_index - 1
. So, again using "warmup" as the example input word --letter_index
is initially set at 5 (str.length-1
) to access the last letter in the string, and then after the first loop iteration, it is reassigned the value of 4, which will correspond tostr[4]
, or the second-to-last character in the input string. So...
# before we begin the loop
reversed_string == ""
letter_index == 5
# after loop 1:
reversed_string == "p" # we added str[5], or "p", into the reversed_string
letter_index == 4 # we subtracted 1 from letter_index
# after loop 2:
reversed_string == "pu" # we added str[4], or "u", into the reversed_string
letter_index == 3 # we subtracted 1 from letter_index
# after loop 3:
reversed_string == "pum" # we added str[3], or "m", into the reversed_string
letter_index == 2 # we subtracted 1 from letter_index
.
.
.
- After we have looped through the code-block logic
str.length
times, the loop breaks, and we return the fullreversed_string
. Note that in Ruby you don't need to explicitly declare areturn
statement on the last line of the method (i.e.return reversed_string
) -- A Ruby method will implicitly return the value of the last evaluated expression, which is different from some other languages. So, we can simply writereversed_string
on the last line of the method body, and that is what will be returned.
If we were to use built-in Ruby methods, we could simply write the entire Ruby method as:
def reverse_string(str)
str.reverse
end
# Or, rather than needlessly writing a new method,
# we would probably just call the existing method on a string:
"whatever your string is".reverse
--
A similar solution in Javascript
function reverseString(str) {
let reversedString = "";
for (let i = str.length - 1; i >= 0; i--){
reversedString += str[i];
}
return reversedString;
}
A couple differences to note...
- Obviously, the syntax for declaring a functions and variables in javascript is different.
- As is the looping syntax. In a Javascript
for loop
, we introduce 3 arguments in the parentheses after the wordfor
. The first (let i = str.length - 1;
) sets the initial value of the iterator variablei
(same as the third line in the Ruby solution). The second (i >= 0
) defines the condition under which the loop will continue to run. So this loop will run whilei>=0
. The third (i--
) executes after each iteration through the loop, in this case decreasing the value ofi
by one after each iteration (that's what the--
operator does). If the initialstr.length
is 6, the intial value ofi
will be 5, and each time the loop runsi
will decrease by 1, untili>=0
is no longer true... so it'll run 6 times (I'll let you count). - In Javascript, we need to explicitly return the value we want output. So we need to say
return reversedString
on the last line of the function.
If we were to use built-in functions, we could take advantage of Javascripts .reverse()
function, which can be used on arrays:
function reverseString(str) {
return str.split('').reverse().join('');
}
I won't walk through this one step-by-step, but essentially in order to use the reverse()
function we need to first split the input string into an array of individual characters using .split()
("warmup"
turns into ['w', 'a', 'r', 'm', 'u', 'p']
). Then, we can .reverse()
the array (turns into ['p', 'u', 'm', 'r', 'a', 'w']
), then we can .join()
the array (turns into "pumraw"
), and return it... all in one line 😯.
Bada bing, bada boom.
--
Thx for reading, love you guys,
noah
Comments
Post a Comment