Andrei Botalov
Andrei Botalov

Reputation: 21096

Is there a way to initialize hash's values lazily?

I have a hash like:

h = {
  a: '/users/sign_up',
  b: "/user/#{@user.id]}"
}

Later I do h[:b].

Hash values are initialized when hash itself is initialized. But I'd want @user.id to be invoked every time when h[:b] is invoked.

It seems to be not possible to do it with Ruby's hash. But is there some workaround to do it?

Upvotes: 0

Views: 359

Answers (2)

megas
megas

Reputation: 21791

h = {}
h.default_proc = proc do |hash, key|
  key == :b ? "/user/#{@user.id}" : nil
end
h[:a] #=> nil
h[:b] #=> "/user/<id>"

Upvotes: 2

Mori
Mori

Reputation: 27789

You can use lambdas for the values of the hash, and call the lambda when the actual value is needed, e.g.:

h = {
  a: ->{'/users/sign_up'},
  b: ->{"/user/#{@user.id}"}
}

h[:b].call

Upvotes: 3

Related Questions