Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does this syntax mean in Ruby? .. tasks.all?(&:complete?) [duplicate]

I'm walking through the example project in the Rails 5 Test Prescriptions - Build a Healthy Codebase (published date: 2018) book and encountering this method:

#pages 29-30 of the book
class Project
  .
  .
  def done?
    tasks.all?(&:complete?) #only this line confused me, especially the `&` part
  end
end

the syntax looks really strange to me since I just learned Ruby & Rails for more than one month..any hints just for pointing me to where I should read would be really appreciated

like image 767
You Nguyen Avatar asked Dec 06 '25 08:12

You Nguyen


1 Answers

& is for passing block to method as a block (also used the other way in parameter list to make implicit block a parameter), it implicitly calls to_proc on passed object.

Symbol#to_proc for :symbol makes a proc{|param| param.symbol }

So your code is equvalent to tasks.all?{|task| task.complete? }

like image 189
Vasfed Avatar answered Dec 07 '25 21:12

Vasfed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!