Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

ruby

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?

like image 472
Roman Avatar asked May 18 '12 01:05

Roman


People also ask

What is :: in Ruby?

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember in Ruby, classes and methods may be considered constants too.

Do Ruby hashes have an order?

Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays.

What is a hash rocket in Ruby?

The fat comma (also termed hash rocket in Ruby and a fat arrow in JavaScript) is a syntactic construction that appears in a position in a function call (or definition) where a comma would usually appear. The original usage refers to the " ) letters :( " construction in ALGOL 60.

What does the colon mean in Ruby?

What is symbol. Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.


2 Answers

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.

like image 194
OzBandit Avatar answered Oct 13 '22 20:10

OzBandit


Ruby 1.8 syntax:

:factory => :user

Ruby 1.9 syntax:

factory: :user

Note that the Ruby 1.8 syntax works in 1.9 also.

like image 28
Kevin Bedell Avatar answered Oct 13 '22 20:10

Kevin Bedell