I’m trying to learn Ruby as well as Ruby on Rails right now. I’m following along with Learning Rails, 1st edition, but I’m having a hard time understanding some of the code.
I generally do work in C, C++, or Java, so Ruby is a pretty big change for me.
I’m currently stumped with the following block of code for a database migrator:
def self.up
create_table :entries do |t|
t.string :name
t.timestamps
end
end
Where is the t variable coming from? What does it actually represent? Is it sort of like the ‘i’ in a for(i=0;i<5;i++) statement?
Also, where is the :entries being defined at? (entries is the name of my controller, but how does this function know about that?)
:entriesis a symbol literal, it’s a literal value like7or"a string". There’s nothing to define (incidentally, the function doesn’t know about the name of your controller).tis the parameter to the block you’ve passed in to thecreate_tablesmethod. What you’ve written here is roughly analogous to something like:in C++.
create_tablecalls your block and passes it a parameter, which you’ve namedt. I would suggest you get an introductory book for ruby as opposed to rails. I recommend Ruby For Rails by David A. Black.