Samuel Hummerstone
Samuel Hummerstone

Reputation: 23

Strange end-of-input error in Ruby

just written a really basic bit of Ruby code, and I can't seem to see what the error is finding wrong with it. I have already tried deleting and redoing all of the 'end' keywords, nothing seems to crack it.

I'm a beginner, so it may be something I haven't noticed. All help will be appreciated. Thanks!

Here is my code:

def is_a_prime(n)
    for 2.upto(n) do |x|
        return false if n % x == 0  
        return true
    end
end
puts is_a_prime(4)

Upvotes: 2

Views: 61

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Here is the fix :

def is_a_prime(n)
  2.upto(n) do |x|
    return false if n % x == 0
  end
  true
end
puts is_a_prime(4)
# >> false

I'd write this prime number check code as :

def is_prime? n
  2.upto(n-1) { |x| return false if n % x == 0 }
  n > 1
end

is_prime? 5 # => true
is_prime? 4 # => false
is_prime? 7 # => true

Upvotes: 4

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Keyword return should be avoided when possible. Whether you think you need return it basically means that you are stuck with a wrong code design.

def is_a_prime(n)
  ! (2...n).each do |x| 
      break nil if (n % x).zero?
  end.nil?
end
puts is_a_prime(4)
puts is_a_prime(7)

Or:

def is_a_prime(n)
  ! (2...n).any? do |x| 
      (n % x).zero?
  end
end

Upvotes: -1

Devon Parsons
Devon Parsons

Reputation: 1288

Drop the for keyword, and move the return true line down below the first end.

Upvotes: 1

Related Questions