jlog
jlog

Reputation: 283

Ruby syntax with hash keys and symbols

With the Rails expression dependent: :destroy, is dependent the hash key and destroy just a symbol?

Upvotes: 0

Views: 453

Answers (2)

tadman
tadman

Reputation: 211590

The notation introduced in Ruby 1.9 is just a shortcut, and you can see what it means using irb:

h = { dependent: :destroy }
# => { :dependent => :destroy }

They're both symbols. Don't forget that a hash can be keyed by any object, not necessarily a symbol or a string. This is completely different from most languages where the key will be coerced into something consistent.

Using that example you can see what the types of the keys and values are:

h.keys
# => [:dependent]

h.values
# => [:destroy]

They're all symbols in this case.

Upvotes: 1

magni-
magni-

Reputation: 2055

Writing has_many :orders, dependent: :destroy is the same as has_many(:orders, {:dependent => :destroy})

:dependent is the key, :destroy the value of the hash passed as an argument to has_many.

Upvotes: 0

Related Questions