Stuck on one liner 'unless' and 'if' statements


#1

Can someone take a look at the following code?

$VERBOSE = nil    # We'll explain this at the end of the lesson.
require 'prime'   # This is a module. We'll cover these soon!

def first_n_primes(n)

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

first_n_primes(10)

where the error is that it takes too long to load.


#2

Is a .... ? Did you mean to write Integer?


#3

Remember that the structure of unless and if are

unless false condition
  DO smth
end

if condition 
  DO smth
end

in your code you forgot the DO part. Or, you have it there, but it's not complete. What you have written is the same as writing it like

unless false condition
  smth
end

if condition
  smth
end

Can you see it? Do you see the pattern and how you should change your shortcode?

DO smth if condition

DO smth unless false condition

#4

ok so basically what I am trying to say is that since you have explicit returns in this exercise and not implicit returns the statement should read

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

return "n must be greater than 0" if n <= 0

I had the same infinite loop problem until including the return keyword before the actual returned value


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.