Hi,
Apologies if this is an overly elementary question, but 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?
Thanks in advance.
-
The code between the first vertical bar and the
end
defines a Ruby block. The wordformat
is a parameter to the block. The block is passed along with the method call, and the called method canyield
values to the block.See any text on Ruby for details, this is a core feature of Ruby that you will see all the time.
rampion : No, the code between the do and the end is a ruby block. The terms between the vertical bars are parameters to that block.John Topley : IIRC, the pipe syntax is borrowed from Smalltalk.Chuck : Yep, except Smalltalk just used one pipe. -
The equivalent in Java would be something like
// Prior definitions interface RespondToHandler { public void doFormatting(FormatThingummy format); } void respondTo(RespondToHandler) { // ... } // Equivalent of your quoted code respondTo(new RespondToHandler(){ public void doFormatting(FormatThingummy format) { format.html(); format.xml(); } });
Brent.Longborough : Hmmmm, no comment.Jon Bright : Brent, if you mean by that, that the Java version is verbose and wordy - yep, I'd agree with you. But then again, this is a less idiomatic construction in Java. Ruby uses it all the time, Java less so.jonnii : the format.html(); format.xml(); part would probably be more like a switch statement, as you'd be switching on the format that was requested. -
I found a great explanation here: Rails for PHP Developers - Ruby Block Scope
-
Parameters for a block sit between the | symbols.
-
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".
0 comments:
Post a Comment