-
[Ruby] exercise _ Pick Primescoding for food 2022. 8. 6. 23:34
Write a method pick_primes that takes in an array of numbers and returns a new array containing only the prime numbers.
def pick_primes(numbers) end print pick_primes([2, 3, 4, 5, 6]) #=> [2, 3, 5] puts print pick_primes([101, 20, 103, 2017]) #=> [101, 103, 2017] puts
# my code def pick_primes(numbers) arr = [] numbers.each do |num| if is_prime(num) arr << num end end return arr end def is_prime(num) if num < 2 return false end (2...num).each do |factor| if num % factor == 0 return false end end return true end print pick_primes([2, 3, 4, 5, 6]) #=> [2, 3, 5] puts print pick_primes([101, 20, 103, 2017]) #=> [101, 103, 2017] puts
#solution def pick_primes(numbers) return numbers.select { |num| prime?(num)} # block return true, that's number you're gonna take. if the block return false, that's number that you don't take into your new array. # Just calling method(prime?) and it's gonna give me a boolean. end def prime?(num) if num < 2 # because any number less than two is not a prime. return false end (2...num).each do |factor| if num % factor == 0 return false end end return true end print pick_primes([2, 3, 4, 5, 6]) #=> [2, 3, 5] puts print pick_primes([101, 20, 103, 2017]) #=> [101, 103, 2017] puts