Sorting an array based on user input

Hey, I have just finished the chapter “Ordering your Library” so I want
to experiment a little more with arrays and sorting. I wrote some code
that gets the user’s input on how many cities he’d like to have
alphabetized, but I’m encountering some problems. Here’s the code:

def alphabetize(arr, rev = false)
if rev == true
arr.sort!
arr.reverse!
else
arr.sort! {|item1, item2| item1 <=> item2}
end
arr.each {|thing| puts “#{thing}” + " "}
end
puts “How many cities would you like to specify?”
n = gets.chomp.to_i
for i in 0…n
puts (i+1).to_s + ". city: "
cities = Array.new(n)
cities[i] = gets.chomp
end
alphabetize(cities)

So basically the user says how many cities he wants to sort and then
specifies which ones. Reading the user’s input works just fine, but
apparently, there’s some problem when the method is being called, since
I keep getting this error:

comparison of NilClass with String failed

It has to be something in the method, right? I’m not that experienced
with Ruby yet, so I’m kind of stuck here and I can’t think of a
solution. Any help would be greatly appreciated!

The simplest thing to start with would be to feed a list into the
function
and see if that works:

cities = %w{london paris bejing tokyo moscow}
alphabetize(cities)

This gives me

bejing
london
moscow
paris
tokyo

So the sort function seems ok. The real problem is this

puts “How many cities would you like to specify?”
n = gets.chomp.to_i
for i in 0…n
puts (i+1).to_s + ". city: "
cities = Array.new(n)
cities[i] = gets.chomp
end

Basically you delete the array every time you go round the loop.

puts “How many cities would you like to specify?”
n = gets.chomp.to_i
cities = Array.new
n.times.each do
puts "City: "
cities << gets.chomp
end

The creation of the array is outside the loop and do things in a more
Ruby
way

On Sun, Nov 24, 2013 at 8:27 PM, Peter H.
[email protected] wrote:

The creation of the array is outside the loop and do things in a more Ruby
way

You could even do

puts “How many cities would you like to specify?”
n = Integer(gets)

cities = Array.new n do
puts "City: "
gets.chomp
end

:slight_smile:

Kind regards

robert

Robert, clever!!! :slight_smile:

On Mon, Nov 25, 2013 at 7:07 AM, Robert K.

Peter H. wrote in post #1128490:

n.times.each do

You probably already know this, but “.each” is redundant.