Search code examples
rubyrails-consolepry

Ruby Block Variable not defined error in one line, but works on do..end block


I don't know how to explain this more, I'm open to suggestions.

Here is an example:

User.last.orders.detect { |user_order| user_order.query.id == 107 }

This doesn't work;

NameError: undefined local variable or method ` user_order' for main:Object
from (pry):51:in `block in <main>'

But this works:

User.last.orders.detect do |user_order|
  user_order.query.id == 107
end

This is just a simple example. I really don't understand why this happens. Thanks!


Solution

  • The problem is you have an additional "non-breaking space" between the pipe and user_order, that's why the message says:

    NameError: undefined local variable or method ` user_order' for main:Object

    Your actual variable is " user_order" not "user_order".

    This commonly happens when pressing alt and space at the same time (on OSX), that's common when opening curly braces for "inline" blocks in Ruby.