ruby 数组自定义排序
在Ruby中对数组排序 (Sorting an array in Ruby)
In this program, we are introducing the concept of command line arguments. Command line arguments can be taken from the users with the help of 'ARGV' keyword. Command line arguments are nothing but the input provided to the program code with the help of command line. We have to sort those command line arguments with the help of any method and provide the sorted strings as the output of the code.
在此程序中,我们将介绍命令行参数的概念。 可以使用“ ARGV”关键字从用户那里获取命令行参数。 命令行参数不过是借助命令行提供给程序代码的输入。 我们必须借助任何方法对这些命令行参数进行排序,并提供排序后的字符串作为代码的输出。
Methods used:
使用的方法:
.length: This method is used to find the length of the object. Here, we are employing it to find the number of arguments provided by the user.
.length :此方法用于查找对象的长度。 在这里,我们使用它来查找用户提供的参数数量。
puts: This is a very common yet important method. It is used to put strings as message on the console. here we are printing elements of array with the help of this method.
puts :这是一种非常常见但重要的方法。 它用于将字符串作为消息放在控制台上。 在这里,我们借助此方法打印数组元素。
Variables used:
使用的变量:
str: This container is used to store the command line arguments.
str :此容器用于存储命令行参数。
ch: It is used to store the temporary string. It is employed during sorting.
ch :用于存储临时字符串。 在排序期间使用。
l: It is storing the value being returned from the str.length function.
l :它存储从str.length函数返回的值。
i: It is a loop variable.
i :这是一个循环变量。
j: It is also a loop variable used for sorting.
j :它也是用于排序的循环变量。
Ruby代码使用命令行参数对数组进行排序 (Ruby code to sort an array with command line arguments)
=begin
Ruby program to sort an array with command line arguments
=end
str = ARGV #taking input from command line
l = str.length
ch = "" #temporary string
for i in 1..l
for j in 0..l-1
#comparison of strings
if(str[j].to_s>str[j+1].to_s)
ch=str[j]
str[j] = str[j+1]
str[j+1]=ch
end
end
end
puts str
Output
输出量
Run 1:
Amisha Satyam Ayush Saksham Nikhil
Amisha
Ayush
Hrithik
Nikhil
Saksham
Satyam
Run 2:
Orange Banana Pineapple Papaya
Apple
Banana
Orange
Papaya
Pineapple
Code logic:
代码逻辑:
In the above code, we are taking strings as input from the command line. These strings are referred to as command-line arguments. We have declared a temporary string named ch. We are applying a very common sorting method in which two loops are employed. Strings are compared and whatever the result comes out, further steps are implemented accordingly.
在上面的代码中,我们将字符串作为命令行的输入。 这些字符串称为命令行参数。 我们已经声明了一个名为ch的临时字符串。 我们正在应用一种非常常见的排序方法,其中采用了两个循环。 比较字符串,无论结果如何,都将相应地执行进一步的步骤。
翻译自: https://www.includehelp.com/ruby/sort-an-array-with-command-line-arguments.aspx
ruby 数组自定义排序