gpt4 book ai didi

ruby - codecademy 在这里错了吗?

转载 作者:太空宇宙 更新时间:2023-11-03 17:52:43 25 4
gpt4 key购买 nike

CodeAcademy 的错误:糟糕,请重试。看起来您的方法在没有收到第二个参数时不会默认按字母顺序排列数组。

    def alphabetize(arr, rev=false)
if rev == true
arr.sort! { |item1, item2| item2 <=> item1 }
else
arr.sort!
end
puts arr
end

alphabetize(["a", "b", "c", "d", "e"])

编辑:以下是本节的目标(很抱歉最初没有包括在内):

1) Add an if/else statement inside your method. If rev is true, it should sort the array reverse-alphabetically; if rev is false (which happens if the user passes false or doesn't pass an argument for rev at all), it should sort the array in alphabetical order.

2) Outside your method, puts the sorted array. (This is so you can see all the fine work your method did.)

3) Call your method on an array of your choice to see it in action!

最佳答案

2) Outside your method, puts the sorted array.

不像你那样在里面。 puts arr 返回 nil,codeacademy 想要数组作为返回值。在外面你应该puts从这个方法外面返回值:

def alphabetize(arr, rev=false)
if rev == true
arr.sort! { |item1, item2| item2 <=> item1 }
else
arr.sort!
end
arr
end

puts alphabetize(["a", "b", "c", "d", "e"])

附言。正如 Wayne Conrad 在评论中指出的那样,sort! 修改您的数组。

arr1=[2,3,1,5,22]
# => [2, 3, 1, 5, 22]
alphabetize arr1
# => [1, 2, 3, 5, 22]
arr1
# => [1, 2, 3, 5, 22] # you didn't want this array changed, right?

如果您不想改变数组,您应该使用不改变数组的普通排序
! 也称为 bang 建议危险方法,在本例中它修改数组。

关于ruby - codecademy 在这里错了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21197448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com