That’s what I learnt today! To a complete novice it sounds more daunting than it actually is and I’m guessing it’s something that happens a lot after the initial stages of writing code.
As the course tells me, refactoring is a way to improve the appearance and/or structure of our code without changing what it does. To me, this is making it prettier, faster, easier to understand which I’m sure is what all good programmers strive for.
In our course this involved a few shortcuts:
- Shortening an “if” statement to one line by replacing with
action if boolean
- Ternary operator – making a statement given a set of criteria is met (or not)
num1 = 1
num2 = 2
puts num1 < num2 ? “One is less than two!” :”One is not less than two.”
- Changing if/elsif/else statements to case/when/then/else statements
when value1 then …..
when value2 then…..
- Using conditional assignments (||=)
- Defining methods – removes need for “return” and tidies up code – can be recalled on later in code
- using .times do function rather than for/loop method
This course instantly helped me on my codewars challenge – “Keep up the loop” – printing out a message in case a variable n is below or higher than a set value. Here I was able to use the ternary operator to write out a message depending on the value of n. I mean…it took me a couple of goes!
1) I forgot my “?”
2) codewars doesn’t like “puts”
…but still I got there!
However my next code wars challenge was less of an accomplishment – reversing the word order of a string. This introduced me to the .string.split.reverse.join(‘ ‘) function – never seen that before!
From my interpretation, the split function places each word in order in an array. Then the .reverse function reverses this word order within the array, and then.join brings them back into a string.
This is going to be a long journey…
Next up – “Blocks, Procs & Lambdas”