55

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:

ArgumentError: tried to create Proc object without a block

Any ideas?

Matt
  • 14,906
  • 27
  • 99
  • 149
Gav
  • 11,062
  • 7
  • 33
  • 35
  • I think you want either a lambda or a block, not both. So in the second case just get rid of the lambda and pass in a block. That should do the same as the first. – jkupferman Sep 28 '09 at 05:28

4 Answers4

78

it's a parser problem. try this

named_scope :admin, (lambda do |company_id| 
  {:conditions => ['company_id = ?', company_id]}
end)
Martin DeMello
  • 11,876
  • 7
  • 49
  • 64
19

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

There's some SO discussion here

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

my_proc = lambda do 
  puts "did it"
end
my_proc.call #=> did it
Community
  • 1
  • 1
Mike Woodhouse
  • 51,832
  • 12
  • 88
  • 127
10

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.

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.

Kelvin
  • 20,119
  • 3
  • 60
  • 68
7

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!
khelll
  • 23,590
  • 15
  • 91
  • 109