Pls i need help, I am stuck and frustrated

Pls can someone help me out, I am trying to use a times loop to get 5 student’s (first and last name) and then store the user’s input i.e first and last name in an array but each time I do this, only the last item gets stored in the array.
Here is what I did;
Students_names = [ ]
5.times do
puts “enter first and last name”
Students_name = gets.chomp.upcase
end
Puts students_name
I want the output to look like this
Students_name = [ CHINA CHINESE, USA AMERICAN, JAPAN JAPANESE, IRAN IRANIAN, GHANA ACCRA].
Also I want to be able to print those out in parallel if I wanted. Thanks in advance.
P:s I am very new to coding

Did you try pushing the names onto the students_name array?

student_array = []

5.times{
  print "Enter first and last name: "
  ans = gets.chomp
  student_array.push(ans)
}

p student_array

Important note! Variables that begin with an uppercase letter are constants in Ruby. i.e. Students_names.

1 Like

Thanks for taking out the time to reply me, i am very grateful. I tried your suggestion and it worked, now i can get on with my assignment after being stuck for days.thanks alot.

G4143, you can simplify to student_array == 5.times.map { ... }; p student_array.

2 Likes

The code will look like this:

student_array = 5.times.map { print("Enter first and last name: ") || STDIN.gets.chomp }
p student_array

Don’t forget the STDIN.gets instead of bare gets (Kernel#gets) because it first looks for a file before asking for user input. So if the OP passes arguments wrongly, s/he will get confused because her/his program may crash or read an existing file!..

@SouravGoswami
Why the short circuit || and not a semi-colon(;)?

print("Enter first and last name: ") || STDIN.gets.chomp

Personally speaking, I hate line breaking with semicolon. I generally don’t break lines with semicolons, and instead I write multiple lines. But here I wanted to write the program in a single line, so I used the || short circuit evaluator here.

On the other hand, the short circuit operator should work perfectly in this scenario, because no matter what, print returns nil… Also, the short circuit evaluators doesn’t make the performance of an app noticeably worse…

Semicolons are also fine :wink:

@Flynaijageh Chener Agwobuo is that you. LOL! The internet is a small place. I get a mail from Ruby Forums and I’m surprised to see it’s about a post you made.

I see you’re learning Ruby. One of my favourite Languages. Wish you good luck.