Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are those pipe symbols for in Ruby?

Tags:

syntax

ruby

What are the pipe symbols for in Ruby?

I'm learning Ruby and RoR, coming from a PHP and Java background, but I keep coming across code like this:

def new    @post = Post.new    respond_to do |format|     format.html # new.html.erb     format.xml { render :xml => @post }   end end 

What is the |format| part doing? What's the equivalent syntax of these pipe symbols in PHP/Java?

like image 836
Philip Morton Avatar asked Mar 20 '09 10:03

Philip Morton


People also ask

What is the pipe operator in Ruby?

The pipeline operator is used to provide the output of the left side to the input of the right side. It explicitly requires that this be the sole argument to the function, of which can be circumvented with currying techniques in both languages to partially apply functions.

What does double pipe mean in Ruby?

It's a conditional assignment. From here: x = find_something() #=>nil x ||= "default" #=>"default" : value of x will be replaced with "default", but only if x is nil or false x ||= "other" #=>"default" : value of x is not replaced if it already is other than nil or false.

What does :+ mean in Ruby?

inject(:+) is not Symbol#to_proc, :+ has no special meaning in the ruby language - it's just a symbol.

What does and mean in Ruby?

The and keyword in Ruby takes two expressions and returns “true” if both are true, and “false” if one or more of them is false. This keyword is an equivalent of && logical operator in Ruby, but with lower precedence.


1 Answers

They are the variables yielded to the block.

def this_method_takes_a_block   yield(5) end  this_method_takes_a_block do |num|   puts num end 

Which outputs "5". A more arcane example:

def this_silly_method_too(num)   yield(num + 5) end  this_silly_method_too(3) do |wtf|   puts wtf + 1 end 

The output is "9".

like image 137
August Lilleaas Avatar answered Sep 24 '22 06:09

August Lilleaas