Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Ruby Syntax [duplicate]

Possible Duplicates:
What is the best way to learn Ruby?
Explain Iterator Syntax on Ruby on Rails

I'm still learning ruby, ruby on rails and such. I'm getting better at understanding all the ruby and rails syntax but this one has me a little stumped.

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @contact_lists }
end

respond_to is a method that takes a proceedure, I think. The two formats look like they may be method calls too, but I don't know.

like image 906
Drew Avatar asked Dec 13 '22 19:12

Drew


2 Answers

respond_to is a method which takes block. The block takes one argument, which here is called format.

Now you call two methods on format. html which you call without arguments. And xml which you call with a block.

This block takes no arguments and contains a call to the render method with a hash as an argument. The hash contains the key :xml and the value @contact_lists.

like image 156
sepp2k Avatar answered Dec 27 '22 11:12

sepp2k


Yeap, you're right.

Ruby method calls are a bit puzzling at first, because you can ommit the parethesis, and they may receive code blocks.

So, this is the explaination:

respond_to do |format| 

Invoke the method respond_to and pass it a block on what to do with the format it will receive.

    format.html # index.html.erb

With that object called format invoke the method html

    format.xml  { render :xml => @contact_lists }

And the method xml which in turns receive another block ( do / en and { } , are different syntax to pass block. )

end

Finish the first block

See this other , other answers.

like image 25
OscarRyz Avatar answered Dec 27 '22 11:12

OscarRyz