How to define / name a block in Ruby?

numbers = 1..10 print numbers.map {|x| x*x} # I want to do: square = {|x| x*x} print numbers.map square 

Because the syntax is more concise. Do I have a way to do this without using def + end ?

+7
source share
3 answers
 square = proc {|x| x**2 } print number.map(&square) 
+13
source

You cannot assign a block to a variable because the block is not really an object as such.

What you can do is assign a Proc object to a variable, and then convert it to a block using the & unary prefix operator:

 numbers = 1..10 print numbers.map {|x| x * x } square = -> x { x * x } print numbers.map &square 
+8
source
 numbers = 1..10 square = lambda{|x| x*x } numbers.map &square 
+1
source

All Articles