【问题标题】:How to specify number of inputs and get these inputs in Ruby? [closed]如何指定输入数量并在 Ruby 中获取这些输入? [关闭]
【发布时间】:2014-06-11 03:03:46
【问题描述】:

我是 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    

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

【问题讨论】:

  • 代码与问题有何关联? (无论如何,您都应该将该代码放在 codereview.stackexchange.com 上)
  • 有什么区别
  • codereview.stackexchange.com 会给你一个建设性的你的工作代码。在 SO 上,如果您想获得好的答案,您应该限制您的代码与问题相关

标签: ruby bubble-sort


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多