Skip to content

Conversation

@dylan-chong
Copy link

Setting the default value to a hash (or empty array, or any other mutable object) can cause mutability/side-effect problems to be introduced. These are very hard and time-consuming to track down.

For example:

u1 = User.new
u1.info[:something] = 1

u2 = User.new
u2.info[:something] # => 1

In the above example, one would expect u2.info[:something] to return nil, however because the default value Hash is shared between all users, u2.info[:something] returns 1.

Using the lambda means that a new Hash will be created each time a new user is created, avoiding the above side-effect issue:

u1 = User.new
u1.info[:something] = 1

u2 = User.new
u2.info[:something] # => nil

Setting the default value to a hash (or empty array, or any other mutable object) can cause mutability/side-effect problems to be introduced. These are very hard and time-consuming to track down.

For example:

    u1 = User.new
    u1.info[:something] = 1

    u2 = User.new
    u2.info[:something] # => 1

In the above example, one would expect `u2.info[:something]` to return `nil`, however because the default value Hash is shared between all users, `u2.info[:something]` returns `1`.

Using the lambda means that a new Hash will be created each time a new user is created, avoiding the above side-effect issue:

    u1 = User.new
    u1.info[:something] = 1

    u2 = User.new
    u2.info[:something] # => nil
with the rest of the readme
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant