Ruby - Arrays - Printing out odd numbers in the Array

2275 views ruby
4

I am looking to print out odd numbers in the array, but when I type in a number, I get the following:

undefined method `%' for [1]:Array
(repl):6:in `block in <main>'
(repl):3:in `times'
(repl):3:in `<main>'

This is what I have currently. Any idea as to what is happening?

numbers = []
puts "Please enter 10 numbers, one at a time."
10.times do 
  puts "Please enter a number"
  numbers << gets.chomp.to_i
  if numbers % 3 ==0
  p numbers
  end
  numbers = numbers + 1
end
puts "Here are the numbers you selected"
p numbers

answered question

You are trying to do numbers % 3, but numbers is an array. maybe you want numbers.last. Also you have numbers + 1, which can't be done.

1 Answer

5

You are trying to do "%" for an array. do "%" for the input number instead and then insert to array. Like

numbers = []
puts "Please enter 10 numbers, one at a time."
10.times do 
  puts "Please enter a number"
  num = gets.chomp.to_i
  if num % 3 ==0

....................

Hope this will solve the issue.

posted this

Have an answer?

JD

Please login first before posting an answer.