Roman
Roman

Reputation: 10403

In Ruby what is the meaning of colon after identifier in a Hash?

I'm learning about Factory Girl and I saw this code:

factory :post do
  association :author, factory: :user, last_name: "Writely"
end

why do factory and last_name have a colon at their end?

Upvotes: 19

Views: 7305

Answers (3)

Monarch Wadia
Monarch Wadia

Reputation: 4956

The other answers are right. There was some speculation regarding the rationale behind this new syntax. This change may have something to do with how Javascript and perhaps other languages handle object literal notation. A need was felt, perhaps, to bring ruby more in-line with how these languages handle object creation.

For example, in JavaScript, we can do:

var person = {
    name: "John",
    age: 42,
    married: false
}

So really, when we're passing factory: :user, what we're really doing is passing {factory: :user}, also written as {:factory => :user}. The 1.9 syntax is intended to make it easier to do something like {factory: "user"}

Upvotes: 0

Kevin Bedell
Kevin Bedell

Reputation: 13404

Ruby 1.8 syntax:

:factory => :user

Ruby 1.9 syntax:

factory: :user

Note that the Ruby 1.8 syntax works in 1.9 also.

Upvotes: 17

OzBandit
OzBandit

Reputation: 1054

The colon in this context denotes a literal Hash.

factory is the Hash key, :user is the value.

The alternative syntax is :factory => :user. They mean the same thing.

Upvotes: 33

Related Questions