给定
30.02 -88.87 10.58 -99.22 107.33
以在不使用CCD_ 1方法的情况下进行排序。我在这方面花了几个小时,但没有取得任何成功。
def simple_sort(list) # I have to start with this method
list = list.split(' ') # I understand i need to .split to get arrays
因为它们是浮动的,我需要一种方法来用to_f
方法.each(&:to_f)
使它们浮动。我以前看到过,但我不确定我是否理解":
"。我以为冒号是物体符号,所以有人能给我解释一下(&:to_f)
吗?
sorted_list = [] #thought of creating an empty array to store the new list
这是变得棘手的部分!我该何去何从?
我想遍历数组中的每个项目,找到最小的数字并将其添加到sorted_list
中
def sort_list(list)
list = list.split(' ').map(&:to_f)
sort = []
while sort.length < list.length
sort << list.min
list.delete(list.min)
end
sort = sort.join(' ')
return sort
end
代替使用<=>,是什么让这个代码工作?
打开IRB并尝试以下操作:
>> foo = '30.02 -88.87 10.58 -99.22 107.33'
"30.02 -88.87 10.58 -99.22 107.33"
>> foo.split
[
[0] "30.02",
[1] "-88.87",
[2] "10.58",
[3] "-99.22",
[4] "107.33"
]
所以split
在空白处断开了字符串,到目前为止还不错。
>> foo.split.each(&:to_f)
[
[0] "30.02",
[1] "-88.87",
[2] "10.58",
[3] "-99.22",
[4] "107.33"
]
嗯。。。值没有改变,所以each
可能没有做你认为它会做的事情。正在尝试map
:
>> foo.split.map(&:to_f)
[
[0] 30.02,
[1] -88.87,
[2] 10.58,
[3] -99.22,
[4] 107.33
]
一旦将值转换为浮点值,就可以很容易地对它们进行排序。
注意:您可以使用sort
0运算符(也称为"太空船")来告诉您一个是否小于、等于或大于另一个,这样就可以很容易地知道何时应该交换它们。例如:
0 <=> 1 # => -1
1 <=> 1 # => 0
2 <=> 1 # => 1
您应该阅读Comparable模块的文档,这使得通过定义<=>(other)
方法向类添加附加功能变得非常容易。
map
允许我们修改/转换数组的元素,而each
只对它们进行迭代。可以使用each
来处理元素,但这通常不是您想要做的,因为map!
可以更容易地转换事物。
关于&:to_f
。这是不久前对Ruby符号的一次破解,它被添加到了Rails中。事实证明,它非常有用,以至于它被引入了Ruby本身。它被称为"要处理的符号",并在"Ruby符号和冒号快捷键"中进行了讨论。