【问题标题】:Why does my function not print the sorted array?为什么我的函数不打印排序后的数组?
【发布时间】:2014-06-16 22:59:51
【问题描述】:
# Methods for calculating
# print out the input that the user entered
def PrintScores(*numbers)
    numbers.each {|x| print x.join(" ")}
    puts
end

#print out the scores in ascending order
def ListScores(*numbers)
    numbers.sort!
    print numbers
end

# Main function
out_file = File.new("out.txt", "w")

puts "Enter the scores you wish to have our stats program look into? "
user_input = gets.chomp

input_array = user_input.split(" ")

input_array.map! do |x|
    x.to_i
end

PrintScores(input_array)
ListScores(input_array)

ListScores 函数仍然按照我输入的顺序打印数组,我不知道为什么。

【问题讨论】:

  • 你应该使用ListScores(numbers)而不是ListScores(*numbers)
  • 不要创建放置或打印的方法。因为 ruby​​ 有一种放置和打印的方法。

标签: ruby arrays sorting methods


【解决方案1】:

ListScores 函数仍然按照我输入的顺序打印数组,我不知道为什么?

在您当前的代码中,input_arrayArray 类的一个实例,它作为参数传递给ListScores 方法。 ListScores 期待 splat arguments,因此 numbers 成为一个包含单个 Array 元素(即 input_array 内容)的 Array。这就是您在尝试对其进行排序时以相同顺序看到数组的原因。

例如:

> user_input = gets.chomp
3 2 8 5 1
 => "3 2 8 5 1" 
> input_array = user_input.split(" ")
 => ["3", "2", "8", "5", "1"] 
>   input_array.map! do |x|
>         x.to_i
>   end
 => [3, 2, 8, 5, 1] 
> ListScores(input_array)
[[3, 2, 8, 5, 1]] => nil ## Notice Array with single Array element [[]]

splat operator(*) 用于需要可变参数列表的方法中。 在您的情况下,您不需要在 PrintScoresListScores 方法中使用 splat 运算符。

def PrintScores(numbers) ## <-- Removed splat operator
    numbers.each {|x| print x.join(" ")}
    puts
end

#print out the scores in ascending order
def ListScores(numbers) ## <-- Removed splat operator
    numbers.sort!
    print numbers
end

样本输出:

>   ListScores(input_array)
 [1, 2, 3, 5, 8] => nil 

注意:建议使用 snake_case 作为方法名称,例如 list_scores 而不是 ListScores

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    相关资源
    最近更新 更多