Haiyuan Zhang
Haiyuan Zhang

Reputation: 42832

Ruby grammar question

I'm new to ruby. So I'm confused by the following lines of code:

class CreateProducts < ActiveRecord::Migration
  def self.up
    create_table :products do |t|
      t.string :title
      t.text :description
      t.string :image_url
      t.decimal :price, :precision => 8, :scale => 2

      t.timestamps
    end
  end

  def self.down
    drop_table :products
  end

end

one of the lines makes me most confused is :

t.string :title

I just can't understand it. So could any of you give me some hint on which part of ruby grammar I need to read in order to understand this single line of code? thanks in advance.

Upvotes: 0

Views: 136

Answers (5)

Tony Delroy
Tony Delroy

Reputation: 106236

I'm guessing a bit here, but as a basis for exploration

:title is a Ruby "symbol" - basically a hack to provide higher-efficiency string-like constants - so t.string :title is a bit like calling a t.string("title") in more popular OO languages, and given you seem to be declaring a record structure for the database, I'd say that's adding a field effectively "called" title with type "string".

Upvotes: 1

Matt Briggs
Matt Briggs

Reputation: 42238

to fully understand that file, you need to understand classes, inheritance, modules, method calling, blocks and symbols.

Upvotes: 0

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369574

This is just normal Ruby messaging syntax.

t.string :title

means

  1. dereference the block local variable t
  2. send the message :string to the object referenced by t and pass the literal symbol :title as the only argument

Upvotes: 3

Rohit
Rohit

Reputation: 5721

Check this out this might prove to be very helpful This file is called migration file it creates the backend for your app Another link

Upvotes: 0

adamk
adamk

Reputation: 439

You will find the answer within Why's poignant guide to Ruby

P.S. It's spelt grammar, but for code we'd usually use the word 'syntax'. :)

Upvotes: 0

Related Questions