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

前端 未结 3 1845
暗喜
暗喜 2021-02-05 08:00

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

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

why do

3条回答
  •  盖世英雄少女心
    2021-02-05 08:27

    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"}

提交回复
热议问题