Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

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
    elsif 
    r == Integer
    arr.push(r)
    puts"yay"
else "Thanks"
end

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,863 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
else
    puts "Your array has numbers in it, here they are:"
    puts numbers
end

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."
end