Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving object's send-method an other method with block

This one works:

Beer.all.send(:sort)

and also it works with block:

Beer.all.sort_by{|b| b.name}
Beer.all.sort_by(&:name)

But when I give a executable block to send-method like this:

Beer.all.send(:sort_by{|b| b.name})
Beer.all.send(:sort_by(&:name))

I get syntax error. Is there any alternative way in Ruby to give an executable block to send-method?

like image 765
samu Avatar asked Feb 20 '15 13:02

samu


2 Answers

You should try something like that :

Beer.all.send(:sort_by) {|b| b.name}
like image 148
Chris Avatar answered Nov 03 '22 01:11

Chris


Blocks are special arguments in Ruby, they are not passed together with the regular arguments inside the parentheses. This doesn't have anything in particular to do with send. send is just a method like any other method, after all, it cannot change the syntax of Ruby.

Blocks are passed after all the other arguments, i.e. like this:

foo.bar(baz, qux) {|sillyname| do_stuff }
like image 44
Jörg W Mittag Avatar answered Nov 03 '22 01:11

Jörg W Mittag