如何在Ruby中指定输入数量并获取这些输入?

时间:2014-04-25 11:56:25

标签: ruby bubble-sort

我是ruby的新手,我正在尝试创建一个程序,询问用户的元素数量,然后输入这些元素,然后对它们进行气泡排序。

  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    

我试图从用户那里获得输入,但它不起作用。有人可以帮我解决如何让用户指定元素数量然后获得这些输入吗?

1 个答案:

答案 0 :(得分:1)

如果您正在寻找将从用户那里获取输入的代码,它将类似于:

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