Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed documentation that implies the introduction of a mutability bug #394

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

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