How to convert array into strings? - ruby

I have an output as such:
require_relative "array_sort"
arraystudents = []
puts "Type a student name:"
name = gets.chomp
arraystudents.push(name)
while name != ""
puts "Type another student name or press enter to finish:"
name = gets.chomp
arraystudents.push(name)
end
puts "Congratulations! Your Array has #{arraystudents.count} students: #{array_sort(arraystudents)}"
Every time I run it, I end up with an array output rather than just having the names under string form.
Is there a way where the output can be along the lines of: x, y and z? Rather than array, or just commas separating each name?
On another note, I seem to also have a blank [0] at the beginning of my array.
Here's on the array_sort.rb file.
def array_sort(students)
return students.sort.join(",")
end
Any help would be appreciated.

You're getting an extra blank entry at the end of arraystudents. arraystudents.sort makes it look at it's at the front.
The problem is because you check if name is empty, then you ask for a name and push it into arraystudents. Ask, push, then check. Instead you need to ask, check, then push.
arraystudents = []
loop do
puts "Type another student name or press enter to finish:"
name = gets.chomp
break if name == ''
arraystudents.push(name)
end
loop is an infinite loop. break lets you exit a loop.
Is there a way where the output can be along the lines of: x, y and z?
Yes. First handle the case when you have 0 or 1 students. This avoids results like and Zara.
When there's multiple students: Sort them. Remove the last student. Join the rest. Then concatenate them.
def display_students(students)
case students.size
when 0, 1
return students.first
else
sorted_students = students.sort
last = sorted_students.pop
return "#{sorted_students.join(', ')} and #{last}"
end
end
There may be more elegant ways, but it gets the job done.

You are inserting an element of the array also on the last iteration
i suggest doing something like this to avoid the last element of the array
arraystudents = []
puts "Type a student name:"
name = gets.chomp
arraystudents.push(name)
loop do
puts "Type another student name or press enter to finish:"
name = gets.chomp
break if name == ""
arraystudents.push(name)
end
puts "Congratulations! Your Array has #{arraystudents.count} students: #{arraystudents.sort.join(',')}"
The codes outputs
Type a student name:
1
Type another student name or press enter to finish:
2
Type another student name or press enter to finish:
3
Type another student name or press enter to finish:
Congratulations! Your Array has 3 students: 1,2,3
If you want to have the "and" you can do
arraystudents = []
puts "Type a student name:"
name = gets.chomp
arraystudents.push(name)
# puts arraystudents.join(',')
loop do
puts "Type another student name or press enter to finish:"
name = gets.chomp
break if name == ""
arraystudents.push(name)
# puts arraystudents.join(',')
end
arraystudents = arraystudents.sort
if (arraystudents.count == 1)
puts "Congratulations! Your Array has 1 students: #{arraystudents[0]}"
else
puts "Congratulations! Your Array has #{arraystudents.count} students: #{arraystudents[0..-2].join(',')} and #{arraystudents[-1]}"
end
and the output will be
Type a student name:
3
Type another student name or press enter to finish:
2
Type another student name or press enter to finish:
1
Type another student name or press enter to finish:
Congratulations! Your Array has 3 students: 1,2 and 3

Related

Asking a user multiple questions using Ruby gets.chomp method

I'm very new to Ruby and practicing with user input. I have coded the following which allows the user to input names of students continuously until they hit return twice. After each input the program returns how many students are in the school, and when they are finished inputting for good, it prints out a list of the students and the cohort they are in.
At the moment, the cohort is hardcoded, and I want to modify this so that I can ask for both the name and the cohort, with the program continuing to ask for this info until the user hits return twice. Any help would really be appreciated - thanks :)
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
students = []
name = gets.chomp
while !name.empty? do
students << {name: name, cohort: cohort}
puts "Now we have #{students.count} students"
name = gets.chomp
end
students
end
def print_header
puts "The students of this Academy".center(50)
puts "-----------".center(50)
end
def print(students)
students.each do |student, index|
puts "#{student[:name]} #{student[:cohort]} cohort"
end
end
end
def print_footer(names)
puts "Overall, we have #{names.count} great students".center(50)
end
students = input_students
print_header
print(students)
print_footer(students)
Instead of a while loop, I'd suggest to use loop do and break in case the name is empty (or also cohort):
loop do
puts "Please enter the names of the students"
name = gets.chomp
break if name.empty?
puts "Please enter the cohort"
cohort = gets.chomp
# break if cohort.empty?
students << {name: name, cohort: cohort}
end

How to terminate Ruby array sort program using Nil entry

Noob rubyist here, working through "Learn to Program." I've set up the below code to take user entries and sort, but I can't figure out how to end the program on a nil entry instead of the 'done' that is currently set. Setting the user == '', obviously terminates before it takes any input. Any help is greatly appreciated!
array = []
user = ''
puts "Type as many words as you like. Press enter to end."
until user == 'done'
user = gets.chomp
array.push user
end
puts
puts array.sort
Start your variable from nil, so that it executes the body at least the first time
user = nil
until user == ''
user = gets.chomp
array.push user
end
Here is another implementation that will not add the blank user to the array. Although it would be nice to use a construct more specific than loop, loop gives us exactly what we need.
users = []
loop do
user = gets.chomp
if user != ''
users << user
else
break
end
end
puts users
Your message says "Press enter to end". So I suggest you get the user input in one go, split the string into words, sort and display.
user = ''
puts "Type as many words as you like. Press enter to end."
user = gets.chomp
array = user.split
puts array.sort

Breaking a loop when a user types a certain input

So I'm trying to break a loop when a user type done and from there jump into another method called "survey" that asks a few leftover questions.
This is what I have a the moment:
def survey
puts "For how many years have you had these allergies?"
name = gets.chomp.to_i
puts "When was your last allergy reaction?"
reaction = gets.chomp.to_i
end
def allergies
puts "Please enter all your allergies. When you are finished, type 'done'."
allergy = gets.chomp.downcase!
while allergy != "done"
# Format the loop so that when the user types 'done'
# The loop breaks and we go to the 'survey' method
allergy = gets.chomp.downcase
survey
if allergy == "nuts"
puts "Beware! The food item contains peanuts!"
break
end
end
end
allergies
At the moment it just lets me type in one allergy and thenk skips right into the survey method. How can I change this so I can keep inputting allergies until I either type "nuts" or "done"?
def survey
puts "For how many years have you had these allergies?"
name = gets.chomp.to_i
puts "When was your last allergy reaction?"
reaction = gets.chomp.to_i
end
def allergies
puts "Please enter all your allergies. When you are finished, type 'done'."
allergy = gets.chomp.downcase!
while allergy != "done"
# Format the loop so that when the user types 'done'
# The loop breaks and we go to the 'survey' method
allergy = gets.chomp.downcase
if allergy == "nuts"
puts "Beware! The food item contains peanuts!"
break
elsif allergy == "done"
survey
end
end
end
allergies
Try an if-else statement
def allergies
puts "Please enter all your allergies. When you are finished, type 'done'."
allergy = gets.chomp.downcase!
while allergy != "done"
if allergy == "nuts"
puts "Beware! The food item contains peanuts!"
break
else
survey
end
allergy = gets.chomp.downcase
end
end

How to create a user defined exception in Ruby from user input

I am trying to create a user defined error where, if the user enters their first name only, it raises an error and tells the user to try again or, if they enter a numeral, it will raise an error.
This is my code but when I run it it outputs "Enter your first and last name" then it rescues it no matter if I enter a full name. It still says "Sorry I didn't quite catch that." then concatenates it:
class MyNewException < Exception
attr_reader :first, :last
def initialize(first)
#first = first
end
end
print "Enter your first and last name: "
begin
first = gets.chomp
last = gets.chomp
#prompt the user to enter first and last name
rescue MyNewException
puts "Sorry I didn't quite catch that. Try again."
gets
else
puts "Hello, " + first + last + "!"
end
gets will grab everything you type before pressing Enter. So first actually includes the first and last name that you are entering, and then last is empty. It looks like they are being concatenated, but all the text is in first. If you enter your first name, then press Enter, then enter your second name, then it should output both names.
The error is not being raised. You need to add something like this if you want to raise the error when last is blank:
last = gets.chomp
if last == ""
raise MyNewException, first
end

How Do You Put 'gets' Input Into An Array?

Ruby noob here learning the ropes. I'm currently going through this tutorial and am working on this exercise:
Let's write a program which asks us to
type in as many words as we want (one
word per line, continuing until we
just press Enter on an empty line),
and which then repeats the words back
to us in alphabetical order.
I'm ignoring the alphabetical order part, for now.
Here is my code:
puts 'Hi, do you need something sorted?'
yn = gets.chomp
while yn != 'no'
puts 'What else?'
array = [gets]
yn = gets.chomp
end
puts 'Here\'s what you told me: ' +array.to_s
I've tweaked this for a few hours. To prevent my laptop from breaking due to an act of frustration I'm taking a break. Can anybody with more experience, and possibly more patience, point out my errors?
Keep in mind that every time you gets is a method that asks the user for input. On your lines:
array = [gets]
yn = gets.chomp
You are actually asking for input twice. Instead, store the user input somewhere (such as the array, see below) and get the stored value rather than asking the user twice.
Further, array = [gets] replaces the existing array with an array containing one element (the user input). You are never building up user input into the array. Instead, initialize the array before the while loop and use << in the loop:
array = Array.new
...
while yn != "no"
...
array << gets.chomp
yn = array.last
...
end
If you're having difficulty with something, the first thing you should do is try something simpler.
Rather than doing gets and looping, just try doing a simple gets.
puts 'Hi, do you need something sorted?'
yn = gets.chomp
Then I'd see if yn was what I expected.
The next thing I'd do is, rather than doing a loop many times, just try it once
puts 'Hi, do you need something sorted?'
yn = gets.chomp
if yn != 'no'
puts 'What else?'
array = [gets]
yn = gets.chomp
STDERR.puts "array is #{array.inspect}"
STDERR.puts "yn is #{yn.inspect}"
end
Then you'd hopefully realize that array and yn are both getting input, which wouldn't make sense.
For more hints on how to debug Ruby code, see How do I debug Ruby scripts?
I was having the same problem. Here is where I ended up (I think it meets all the specifications from the question):
puts 'Type in as many words as you\'d like. When you\'re finished, press enter on an empty line'
array = []
input = ' '
while input != ''
input = gets.chomp
array.push input
end
puts
puts array.sort
while yn != "no"
array << yn
print "What else? "
yn = gets.chomp
end
The "<<" appends yn to your array. (The only reason I used print is because it puts the cursor right next to the question mark instead of on the next line. No other reason)
#encoding:utf-8
x = Array.new
puts "enter something:".capitalize
y = ''
while y !=#nill
y = gets.chomp
x.push y
end
x.delete ('')
x.compact
puts "You entered: " + x.sort.to_s
puts "Objects in array: " + x.size.to_s
#made by ~Pick#chu!!!
Another way to read ‘Arrays’ from the console could be:
1: print “enter the values: ”
2: a = gets.chomp # input: “tom mark rosiel suresh albert”
3: array = a.split(‘ ‘) # .split() method return an array
4: p array # ["tom, "mark, "rosiel", "suresh", "albert"]
now, lets say you want an array of integers, all you have to do is:
# input “1 2 3 4 5″
3: array = a.split(‘ ‘).map{ |value| value.to_i }
4: p array # [1, 2, 3, 4, 5]
the clue here is to use a standard separator in order to use the .split() function.
here is how I've done this program:
array = [ ]
input = gets.chomp
while
input != ''
array.push input
input = gets.chomp
end
puts array
puts
puts array.sort

Resources