views:

1182

answers:

3

Hi,

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? Thanks in advance!

Gav

+3  A: 

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
Mike Woodhouse
Thanks Mike, had a look a the other thread. :-)
Gav
+2  A: 

it's a parser problem. try this

named_scope :admin, (lambda do |company_id| 
  {:conditions => ['company_id = ?', company_id]}
end)
Martin DeMello
I'm not sure it's 'a parser problem', but your code should fix it.
khelll
Chose this as my answer since it let me have my do...end cake. Thanks Martin.
Gav
khelll: yeah, 'problem' is a bit of a misstatement, i'll admit. it's a matter of the lower precedence of do...end, as mike woodhouse explains.
Martin DeMello
+2  A: 

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