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

Why won't this work?

{ print x |x} }

What about y?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • What is everyone talking about parameters? what does that mean!? I'm not used to lambda expressions. – TIMEX Aug 23 '10 at 08:45
  • 1
    Parameters are the things you pass to a function. This isn't something special to lambdas. http://en.wikipedia.org/wiki/Parameter_%28computer_science%29 – Chuck Aug 23 '10 at 08:47
  • 1
    Is the |x| always written exactly right after the "{"? – TIMEX Aug 23 '10 at 08:55
  • Yes, always immediately after the `{`, or after the `do` if you are using `do` and `end` for your block. – mikej Aug 23 '10 at 09:03
  • I highly recommend you read "Why's Poignant Guide to Ruby" and the Ruby "Pickaxe" Book. Both are free; Google them. – maček Aug 23 '10 at 21:05
  • 1
    possible duplicate of [What are those pipe symbols for in Ruby?](http://stackoverflow.com/questions/665576/what-are-those-pipe-symbols-for-in-ruby) – Andrew Grimm Oct 31 '11 at 00:17

4 Answers4

10

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}" }
mikej
  • 65,295
  • 17
  • 152
  • 131
3

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.

Ashwin Phatak
  • 645
  • 5
  • 8
1

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
Chuck
  • 234,037
  • 30
  • 302
  • 389
0

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
Swanand
  • 12,317
  • 7
  • 45
  • 62