In Ruby, what are the vertical lines?

1.upto(9) { |x| print x } 

Why is this not working?

 { print x |x} } 

What about y ?

+4
source share
4 answers

This is for the parameters that are passed to your block. those. in your example, upto will call your block with every number from 1 to 9, and the current value is available as x .

Block parameters can have any name, like method parameters. for example 1.upto(9) { |num| puts num } 1.upto(9) { |num| puts num } .

Like method parameters, you can also have several parameters for a block. eg

 hash.each_pair { |key, value| puts "#{key} is #{value}" } 
+7
source

Vertical lines are used to indicate parameters for a block. A block is code enclosed inside {}. This is really the syntax of the ruby ​​block, the parameters for the block, and then the code.

+1
source

This is not an operator; it limits the argument list for the block. Fonts are equivalent to paranas in def foo(x) . You cannot write it as {print x |x} for the same reason:

 def foo(x) puts "It #{x}" end 

cannot be rewritten as follows:

 def foo puts "It #{x}" (x end 
+1
source

In the code snippet you specified, the vertical lines are part of the block definition syntax. Thus, { |x| print x } { |x| print x } is a block of code provided as an argument to the upto method, 9 also a parameter passed to the upto method.

A block of code is represented by a lambda or a Proc class object in Ruby. lambda in this case is an anonymous function.

To simply draw an analogy with the function definition syntax,

 def function_name(foo, bar, baz) # Do something end { # def function_name (Does not need a name, since its anonymous) |x| # (foo, bar, baz) print x # # Do Something } # end 
0
source

All Articles