Pav*_*van 2 ruby ruby-on-rails ruby-on-rails-4
命名范围(或Rails 4中的范围),Lambdas和Procs之间的确切区别是什么?
在Lambda和Proc之间,选哪一个?
1. Proc不会检查传递的参数,但lambda会检查
proc1 = Proc.new { |a, b| a + 5 }
proc1.call(2) # call with only one parameter
=> 7 # no error, unless the block uses the 2nd parameter
lambda1 = lambda { |a, b| a + 5 }
lambda1.call(2)
=> ArgumentError: wrong number of arguments (1 for 2)
Run Code Online (Sandbox Code Playgroud)
仅当块使用第二个参数时,Proc才会抛出错误.
proc2 = Proc.new { |a, b| a + b }
proc2.call(2) # call with only one parameter
=> TypeError: nil can't be coerced into Fixnum
Run Code Online (Sandbox Code Playgroud)
2. Proc从调用方法返回,而lambda没有
def meth1
Proc.new { return 'return from proc' }.call
return 'return from method'
end
puts meth1
=> return from proc
def meth2
lambda { return 'return from lambda' }.call
return 'return from method'
end
puts meth2
=> return from method
Run Code Online (Sandbox Code Playgroud)
如果没有在方法中调用它们,
proc1 = Proc.new { return "Thank you" }
proc1.call
=> LocalJumpError: unexpected return
lambda1 = lambda { return "Thank you" }
lambda1.call
=> "Thank you"
Run Code Online (Sandbox Code Playgroud)
3.范围/命名范围是特征 Rails
它用于指定常用查询,这些查询可以作为关联对象或模型上的方法调用引用
例如,在user.rb中:
scope :developers, -> { where(:role => 'developer') }
Run Code Online (Sandbox Code Playgroud)
你可以用它作为
@developers = User.developers
Run Code Online (Sandbox Code Playgroud)
范围是可链接的,因此您可以进行查询
@developers = User.developers.where(:age => 40)
Run Code Online (Sandbox Code Playgroud)
示例中定义的范围与定义类方法完全相同,如下所示.
def self.developers
where(:role => 'developer')
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
970 次 |
| 最近记录: |