Diego
Diego

Reputation: 610

What is the double pipes in Ruby ( not the ||= )?

Can anyone explain to me what the double pipes, |i|, represent or are called in this example?

(1..10).detect {|i| (1..10).include?(i * 3)}

Upvotes: 2

Views: 303

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118261

That's the syntax to declare the block parameters in Ruby.

Read the Cycling and Looping—a.k.a. Iteration

Let’s look at that iterator in more depth:

@names.each do |name|
  puts "Hello #{name}!"
end

#each is a method that accepts a block of code then runs that block of code for every element in a list, and the bit between do and end is just such a block. A block is like an anonymous function or lambda. The variable between pipe characters is the parameter for this block.

Upvotes: 4

Harsh Gupta
Harsh Gupta

Reputation: 4538

They are syntax for parameters for blocks or Procs in Ruby.

Upvotes: 0

Related Questions