Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Alphonse Cuccurullo
Alphonse Cuccurullo
2,513 Points

Hi there can someone help with my syntax?

arr = []
puts arr
if arr.empty?
    puts "What it's empty? add some numbers."
    r = gets.chomp.to_i
    r == Integer
else "Thanks"

so the goal here is to is too add numbers too the array if the array is empty. i concidered a while loop but am wondering if its possible to pull this off with the if statement if not then combined with the while loop.

1 Answer

Tim Knight
Tim Knight
28,888 Points

If you're just trying to see if the array is empty and then add the response to it if it's not you could do something like this:

numbers = []
puts numbers
if numbers.empty?
    puts "Your array is empty, please add a number."
    numbers << gets.chomp.to_i
    puts "Your array has numbers in it, here they are:"
    puts numbers

You could include a while loop as well, but you'd want to determine what ends the program. Would it be the length of the array? You could also print menu like they do in some of the Ruby exercises where one key press equals to add a new number and another one exits the program something like this:

def print_menu
  puts "Press an option to continue:"
  puts "\t1. Add a number to the array."
  puts "\t2. Exit the program."