StarkTsorian
StarkTsorian

Reputation: 27

How do you pass a range of values as arguments to a method?

I am calling a method I created and trying to pass a range of values as the arguments.

My code:

def prime_numbers (x)

  i = 1
  count = 0


  until i > x

    if x % i == 0
      count += 1
    end 

    i += 1 

  end

  if count > 2
    puts "count is: " + count.to_s
    p x.to_s + " is not prime."
    p false

  elsif count == 2
    puts "count is: " + count.to_s
    p x.to_s + " is prime."
    p true
  end

end

prime_numbers (5)
puts
prime_numbers (25)
puts
prime_numbers (31)
puts
prime_numbers (1..100) #This is the one I care about that is throwing an error

Desired output:

count is: 2 "5 is prime." true

count is: 3 "25 is not prime." false

count is: 2 "31 is prime." true

This would be desired for all the numbers within the range.

What I think I've done incorrectly or may still need to do:

  1. I could use an array and somehow incorporate blocks to do all of this.
  2. I'm missing something very simple in my syntax
  3. Syntax in my parameter list needs to be changed

Thank you in advance for your time answering this.

Upvotes: 0

Views: 728

Answers (2)

rkalra
rkalra

Reputation: 375

In order to pass an array, you should define a method in a way that it can process an array.

In your code from what I can see is you are getting a parameter x and then applying an operator > to that which in case of a range will throw an error.

When (1..100) is passed as an argument x becomes an array what you might wanna do is something like this

def prime_numbers (x)
  y = x.class == Range ? x : [x]          # to make sure you have an array
  y.each do |number|
    ...... you code here
  end
end

PS you would want to replace number in the above example. Or you could rename your parameter x

Upvotes: 1

steenslag
steenslag

Reputation: 80065

Your method is named prime_numbers, but that is not exactly what it does. It is hard to come up with a good name: it does too much. That said, you could call it for every number in a range like this :

(1..100).each{|n| prime_numbers(n) }

Upvotes: 2

Related Questions