Skip to content

Instantly share code, notes, and snippets.

@jendiamond
Last active April 19, 2016 22:19
Show Gist options
  • Select an option

  • Save jendiamond/eac522f72b3012183acbdb987cb787e1 to your computer and use it in GitHub Desktop.

Select an option

Save jendiamond/eac522f72b3012183acbdb987cb787e1 to your computer and use it in GitHub Desktop.

Refactor

https://www.codecademy.com/en/courses/ruby-beginner-en-Zjd2y/0/1

$VERBOSE = nil
require 'prime'

def first_n_primes(n)

  unless n.is_a? Integer
    return "n must be an integer."
  end

  if n <= 0
    return "n must be greater than 0."
  end
  
  prime_array = [] if prime_array.nil?
  
  prime = Prime.new
  for num in (1..n)
    prime_array.push(prime.next)
  end
  return prime_array
end

first_n_primes(10)

refactor 1

First up, on line 14, our hapless programmer has decided to check whether prime_array has a value by using the .nil? method, which returns true if a value is nil and false otherwise. This isn't a bad idea, and he even has the one-line if statement right!

However, there's a better way—we can use conditional assignment to set prime_array to [] rather than bother with the .nil? check.

Refactor the code on line 14 to use conditional assignment to set prime_array to [] instead of using an if statement.


refactor 2

Omit Needless Words If you've taken a writing class, you might have come across Strunk & White's The Elements of Style. One of their suggestions is to omit needless words, and it applies just as much to writing Ruby as writing essays.

There are two control structures to change here:

The unless on line 6 The if on line 10

Refactor the code in the editor to use single-line ifs and unlesss.


refactor 3

We can remove even more, however. There's one return statement in this code that we can change from explicit to implicit!

Recall that Ruby will automatically return the value of the last expression it evaluates.

Find the unnecessary return keyword and remove it.


refactor 4

Now we'll want to attack that funky-looking for loop. Let's go ahead and replace it with a nice n.times.

Replace the for loop with a call to .times.


refactor 5

Take out the .push and use the concatenation operator instead.

Replace the call to .push with the << operator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment