I've been trying to teach myself Ruby. I've found a few code problems to try solving, but I'm stuck. Here is what I have and the problems I'm trying to solve.
My algorithm is as follows:
- Prompt the user to enter a number between 1 and 10 (inclusive).
- Read that number into an appropriately named variable.
- Test that the number lies in the appropriate range.
- Input new number if it is out of bounds as per the condition.
- Use the number entered by the user to create an array with that number of elements.
- Write a loop which will run through a number of iterations equal to the size of the array.
- Each time through, prompt the user to enter a text string - a name (names of cars, that sort of thing).
- Once the array is entered, display the contents of the array three items to a line.
You will want a for loop for this, and within the for loop you should include a decision which will insert a line break at the appropriate places.
Also,
- Separate the array elements with dashes - but do not put a dash before the first element on a line, and do not put a dash after the last element on a line.
- Use a Ruby function to sort the array alphabetically, then display it again, the same way as before.
- Reverse the order of the array
Display its contents a third time, again putting three elements on each line of output and placing dashes the way you did with the first display effort.
loop do print "Enter an integer between 1 and 10: " s = gets.chomp.to_i if s >0 && s <= 10 break else puts "Interger entered is outside specified range." end end array=[] array.size loop do print "Enter name of a car model: " car=gets.chomp array<<car for i in array array.slice(1..9) {|car| puts car.join(", ") } end end
(1..10).include?(...)as a better idiom for number range inclusion tests. Thearray.sizeline has no effect.