1.upto(9) { |x| print x }
Why won't { print x |x} }
work? What about y?
1.upto(9) { |x| print x }
Why won't { print x |x} }
work? What about y?
It's for the parameters that are being passed to your block. i.e. in your example, upto
will call your block with each number from 1 to 9 and the current value is available as x
.
The block parameters can have any name, just like method parameters. e.g. 1.upto(9) { |num| puts num }
is valid.
Just like parameters to a method you can also have multiple parameters to a block. e.g.
hash.each_pair { |key, value| puts "#{key} is #{value}" }
The vertical lines are use to denote parameters to the block. The block is the code enclosed within { }. This is really the syntax of the ruby block, parameters to the block and then the code.
It's not an operator; it's delimiting the argument list for the block. The bars are equivalent to the parens in def foo(x)
. You can't write it as {print x |x}
for the same reason this:
def foo(x)
puts "It's #{x}"
end
can't be rewritten as this:
def foo
puts "It's #{x}" (x
end
In the piece of code you have specified, vertical lines are a part of the block definition syntax. So { |x| print x }
is a block of code provided as a parameter to the upto
method, 9
is also a parameter passed to the upto
method.
Block of code is represented by a lambda
or an object of class Proc
in Ruby. lambda
in this case is an anonymous function.
So just to draw an analogy to 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