ruby - codecademy 在这里错了吗?

标签 ruby

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/

相关文章:

ruby-on-rails - Rails 3.2.3 命名空间 Controller 被具有相同名称的全局 Controller 覆盖

ruby - 检查 Chef 中的环境变量 only-if guard

ruby - STDIN 和 Powershell - 如何使编码匹配?

ruby-on-rails - 无法访问本地主机 :3000 ruby on rails ubuntu

ruby-on-rails - 将日期解析为 Rails 友好的格式

Ruby - 远程文件下载...超时?

ruby - 带有 ruby​​ 1.9.3 的 Heroku 导致许多不同的崩溃

python - 动态语言中依赖注入(inject)的真实示例是什么?

javascript - Vanilla js 无法在我的 Rails 应用程序上运行?

ruby - 我如何使用 gsub 将正则表达式 ruby​​ 替换为第 10 组?