0

I am a beginner of Rails. I want to ask you about Default Scope. Why does default_scope use 'lambda'? Please take a look at the class below.

Class Category < ActiveRecord::Base
  default_scope labmda { order('categories.name') }
end

Why not a typical block used instead of lambda?

To summarize my questions,

  1. What is lambda?
  2. Why is lambda used in default scope?
1

1 Answer 1

1

lambdas are basically a way to save a block or an anonymous function (like you do in javascript all the time). If you don't know what a block is...

[1,3,5,6].map { |n| n * 2 }

The stuff in the braces (or between the do and end statement} is a block.

So instead of rewriting the block a bunch of times, you could save it like so:

my_lambda = lambda { |n| n * 2 }

And you can call it like so:

[1,3,5,6].map(&my_lambda)

Like Sergio said, you don't really need to lambda there. But I suppose you could save the block somewhere else and then use it with default_scope for it and several other classes.

Sign up to request clarification or add additional context in comments.

3 Comments

Now I see lambda lets us reuse block like we do in method. I also understand the 'lambda' is not needed in the class above. So you mean 'default_scope { order('categories.name') }' works fine without lambda? Why was lambda used in the first place when not using it works fine?
I don't know for sure, but I would guess it either used to be required in old versions of rails, or whoever wrote that didn't know if it was required or not and just threw it in there and it worked so kept it. Blocks, procs, and lambdas are covered pretty well on codecademy. I suggest going through it (it's pretty short) to see a bunch of useful cases for using them. Also, please accept my answer if you find it satisfactory.
According to the book in which the code above was quoted, lambda is used in default scope. The book is 'Beginning Rails 4, 3rd Edition'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.