NewbieD NewbieD - 1 month ago 7
Ruby Question

Generate largest number of 10 inputs

New to scripting here. Basically, I am needing to write a program to accept 10 input numbers and return the largest in the list.

I have this code, but obviously it is not running:

class Generator

def getNumbers
number = Array.new

puts "To begin, You will need to enter your numbers."
print "Press Enter to continue."
Console_Screen.pause

10.times do
print "\nPlease enter any number: "
input = STDIN.gets
input.chop!
list.push
return list
end

list.push(number)
print list.max
end
end


Console_Screen.new
Find = Generator.new

end


Can anyone help me with what I coded incorrectly?

Answer

There are many problems with your code. Among them I may point:

1) You created an array named number to store your numbers and then tried to push them to another variable named list;

2) As @tadman pointed, you used a return inside a times block and this makes the block to be executed only once;

3) You never invoked getNumbers to make your process really happen!

This code would do what you need:

class Generator

  def get_numbers
    numbers = Array.new

    puts "To begin, You will need to enter your numbers."
    puts

    10.times do
      print "\nPlease enter any number: "
      input = STDIN.gets
      input.chop!
      numbers.push(input.to_i)
    end

    print numbers.max
  end
end

Find = Generator.new
Find.get_numbers

Notice that I changed the name of your method from getNumbers to get_numbers, which is much more Ruby-like.

Notice that I also changed the name of your array from number to numbers, 'cause it will store numbers, not a single number. Naming your varables correctly may help you to think correctly about your problem. It also helps when it comes for other people reading your program. Even you, six months later, will have problems to understand your own code if you don't name things correctly an comment you code well.

By the way, I also pushed the numbers to numbers as integer, using #to_i. This will make the numbers be compared as numbers, not as strings. If you researsh a bit you'll find out this could be a bit different. If someone enters 0300 as a number, it will be considered to be smaller then 200 as string, but when converted to integers, they will be in the correct order.

Comments