Ruby 中的 lambda 帮助
我是 Ruby 新手,正在尝试将 sort_by lambda 传递给格式方法,如下所示:
sort_by_methods = [ lambda {|l, r| compare_by_gender_then_last_name(l, r)},
lambda {|l, r| compare_by_something_else(l, r)},
lambda {|l, r| compare_by_another(l, r)}]
formatted_output = ""
sort_by_methods.each do |sort_by|
formatted_output << formatter.format(students) { sort_by }
end
格式方法代码看起来像这样:
def format(students, &sort_by)
sorted_students = students.sort { |l, r| sort_by.call(l, r) } // error from this line
sorted_students.each { |s| result << s.to_s << "\n" }
end
出于某种原因,我收到关于上述格式方法代码中的行的解释器投诉(学生。种类.....): “在sort'中:未定义的方法
>” for # (NoMethodError)"
我做错了什么?我假设我已经搞乱了传递 lambda 的语法,但不知道如何实现。
谢谢。
I'm new to Ruby and am trying to pass a sort_by lambda to a format method, like this:
sort_by_methods = [ lambda {|l, r| compare_by_gender_then_last_name(l, r)},
lambda {|l, r| compare_by_something_else(l, r)},
lambda {|l, r| compare_by_another(l, r)}]
formatted_output = ""
sort_by_methods.each do |sort_by|
formatted_output << formatter.format(students) { sort_by }
end
The format method code looks something like:
def format(students, &sort_by)
sorted_students = students.sort { |l, r| sort_by.call(l, r) } // error from this line
sorted_students.each { |s| result << s.to_s << "\n" }
end
For some reason I am getting a interpreter complaint about the line in the above format method code (students.sort.....):
"in sort': undefined method
>' for # (NoMethodError)"
What am I doing wrong? I assume I have messed the syntax for passing lambdas around, but cant figure out how.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题出在这一行:
使用不接受参数并返回 +sort_by+ 块的块调用 format() 。这就是为什么稍后 sort_by.call(l, r) 会失败的原因。该块不接受任何参数。
如果你像这样改变它,它应该起作用:
特殊的&语法表明 sort_by 是一个块,它像 { } 符号一样传递。
The problem is in this line:
format() gets called with a block that accepts no arguments and returns the +sort_by+ block. This is why, later sort_by.call(l, r) will flunk. The block doesn't accept any arguments.
If you change it like this, it should work:
The special & syntax indicates that sort_by is a block, which gets passed like the { } notation.
首先,如果这不起作用,我深表歉意。我手头没有 Ruby 解释器。
将 lambda 作为参数传递可能会更好:
否则您将必须向块添加参数,然后屈服于该块。调用类似于:
定义如下:
第一个解决方案对我来说似乎更清晰。第二个使用隐式块。明确的块会让它更清晰一些。
First, I apologize if this doesn't work. I don't have a Ruby interpreter handy.
It might be better to pass the lambda as a parameter:
Otherwise you're going to have to add parameters to your block and then yield to that block. The call would be something like:
With a definition like:
The first solution seems clearer to me. The second uses an implicit block. An explicit block would make it a bit clearer.