Search code examples
rubybubble-sort

How to specify number of inputs and get these inputs in Ruby?


I'm new to ruby, I'm trying to create a program that asks the user for number of elements, then input those elements, and then bubbles sort them.

  class BubbleSort
    def sort(to_sort)
      # move the array to sort into a variable, which will be used for recursion
      arr_to_sort = to_sort
      # assume that we haven't swapped any values yet
      swapped = false
      # lower the length by one because we can't compare the last value since it's at the end
      length_of_sort = arr_to_sort.length - 1
      # begin loop through each value
      length_of_sort.times.each do |i|
        # if the value we're on is greater than the value to the left of it, swap
        if arr_to_sort[i] > arr_to_sort[i+1]
          # store values to be swapped
          a, b = arr_to_sort[i], arr_to_sort[i+1]
          # remove value we're on
          arr_to_sort.delete_at(i)
          # insert the value to the right, moving the lesser value to the left
          arr_to_sort.insert(i+1, a)
          # swap is true since we did a swap during this pass
          swapped = true
        end
      end
      if swapped == false
        # no swaps, return sorted array
        return arr_to_sort
      else
        # swaps were true, pass array to sort method
        bubble_sort = BubbleSort.new
        bubble_sort.sort(arr_to_sort)
      end
    end
  end    

I tried to get inputs from the user, but it doesn't work. Can someone help me out on how to make the user specifies the number of elements and then get these inputs?


Solution

  • If you are looking for code which will take input from the user, it will be something like following:

    puts "Enter Number of Elements"
    n = gets.chomp
    puts "Enter #{n} elements"
    n.to_i.times do 
      (arr ||= []) << gets.chomp
    end