1

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
5
  • 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 Commented May 26, 2016 at 2:03
  • 2
    FYI, no one wants to read that much text. Commented May 26, 2016 at 2:06
  • 2
    You forgot to describe the problem you're experiencing. Commented May 26, 2016 at 2:22
  • When I enter a car model, the loop continues until I use Ctrl+C. and it is not outputting the desired array 3 elements per line. Commented May 26, 2016 at 2:25
  • 1
    There are several problems with your code. I suggest breaking down your large problem into smaller ones. Verify that the first loop works before proceeding...and so on. Your loops have problems regarding exit conditions. Check out (1..10).include?(...) as a better idiom for number range inclusion tests. The array.size line has no effect. Commented May 26, 2016 at 2:40

2 Answers 2

1

Is that solution you looking for?

loop do
  print "Enter an integer between 1 and 10: "
  s = gets.chomp.to_i

  if (1..10).include?(s)
    arr = [""] * s
    i = 0
    while i < arr.length
      print "Enter name of a car model: "
      car = gets.chomp
      arr[i] = car
      i += 1
    end

    puts arr.join(", ")
    break
  else
    puts "Interger entered is outside specified range."
    break
  end
end

Result is:

[retgoat@iMac-Roman ~/temp]$ ruby loop.rb
Enter an integer between 1 and 10: 2
Enter name of a car model: car_a
Enter name of a car model: car_b
car_a, car_b

UPDATE

Below solution to print an array by 3 elements per line with natural sorting

loop do
  print "Enter an integer between 1 and 10: "
  s = gets.chomp.to_i

  if (1..10).include?(s)
    arr = [""] * s
    i = 0
    while i < arr.length
      print "Enter name of a car model: "
      car = gets.chomp
      arr[i] = car
      i += 1
    end

    puts arr.sort.each_slice(3){ |e| puts "#{e.join(", ")}\n"}
    break
  else
    puts "Interger entered is outside specified range."
    break
  end
end

Result is:

[retgoat@iMac-Roman ~/temp]$ ruby loop.rb
Enter an integer between 1 and 10: 4
Enter name of a car model: z
Enter name of a car model: a
Enter name of a car model: x
Enter name of a car model: b
a, b, x
z

And reverse sorting:

loop do
  print "Enter an integer between 1 and 10: "
  s = gets.chomp.to_i

  if (1..10).include?(s)
    arr = [""] * s
    i = 0
    while i < arr.length
      print "Enter name of a car model: "
      car = gets.chomp
      arr[i] = car
      i += 1
    end

    puts arr.sort{ |x, y| y <=> x }.each_slice(3){ |e| puts "#{e.join(", ")}\n"}
    break
  else
    puts "Interger entered is outside specified range."
    break
  end
end

Result is:

[retgoat@iMac-Roman ~/temp]$ ruby loop.rb
Enter an integer between 1 and 10: 4
Enter name of a car model: z
Enter name of a car model: a
Enter name of a car model: x
Enter name of a car model: b
z, x, b
a
Sign up to request clarification or add additional context in comments.

3 Comments

This is getting closer. I need to output 3 elements per line. If i have 7 elements it should output on 3 lines with the first 2 lines having three elements and the 3rd line with one element.
To do this the directions state to use a for loop. I figured out how to add the dashes in place of the comma. Then I need to sort and output it in alphabetical order, and then reverse the order.
Using a for loop is discouraged in Ruby, there are so many better ways to accomplish the same thing. See github.com/bbatsov/ruby-style-guide and search the page for 'do not use for'.
1

It's better to split you program into small pieces. Also, try not to use loop without necessity.

# Specify Exception class for your context
class ValidationException < RuntimeError
end

def number_of_cars_from_input
  # Get user input
  print 'Enter an integer between 1 and 10: '
  number = gets.chomp.to_i
  # Validate input for your requirements
  unless (1..10).cover?(number)
    raise ValidationException, 'Interger entered is outside specified range.'
  end
  number
rescue ValidationException => err
  # Print exception and retry current method
  puts err
  retry
end

# Get car name from user input
def car_from_input
  print 'Enter name of a car model: '
  gets.chomp
end

# Create array with size equal to number from imput and fill it with cars
array_of_cars = Array.new(number_of_cars_from_input) { car_from_input }
# Separate cars in groups by 3 and join groups
puts array_of_cars.each_slice(3).map { |a| a.join(', ') }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.