Ruby-on-rails Rails:named_scope、lambda 和块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1476678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:47:46  来源:igfitidea点击:

Rails: named_scope, lambda and blocks

ruby-on-railsrubylambda

提问by Gav

I thought the following two were equivalent:

我认为以下两个是等效的:

named_scope :admin, lambda { |company_id| {:conditions => ['company_id = ?', company_id]} }

named_scope :admin, lambda do |company_id| 
  {:conditions => ['company_id = ?', company_id]}
end

but Ruby is complaining:

但 Ruby 抱怨:

ArgumentError: tried to create Proc object without a block

Any ideas?

有任何想法吗?

回答by Martin DeMello

it's a parser problem. try this

这是一个解析器问题。尝试这个

named_scope :admin, (lambda do |company_id| 
  {:conditions => ['company_id = ?', company_id]}
end)

回答by Mike Woodhouse

I think the problem may be related to the difference in precedence between {...}and do...end

我认为问题可能与{...}和之间的优先级差异有关do...end

There's some SO discussion here

这里也有一些SO讨论这里

I think assigning a lambda to a variable (which would be a Proc) couldbe done with a do ... end:

我认为将 lambda 分配给一个变量(这将是一个 Proc)可以通过以下方式完成do ... end

my_proc = lambda do 
  puts "did it"
end
my_proc.call #=> did it

回答by Kelvin

If you're on ruby 1.9 or later 1, you can use the lambda literal (arrow syntax), which has high enough precedence to prevent the method call from "stealing" the block from the lambda.

如果您使用的是 ruby​​ 1.9 或更高版本1,则可以使用 lambda 文字(箭头语法),它具有足够高的优先级以防止方法调用从 lambda 中“窃取”块。

named_scope :admin, ->(company_id) do 
  {:conditions => ['company_id = ?', company_id]}
end


1 The first stable Ruby 1.9.1 release was 2009-01-30.

1 第一个稳定的 Ruby 1.9.1 版本是 2009-01-30。

回答by khelll

It's something related to precedence as I can tell

据我所知,这与优先级有关

1.upto 3 do # No parentheses, block delimited with do/end
  |x| puts x 
end

1.upto 3 {|x| puts x } # Syntax Error: trying to pass a block to 3!