K
Kirk Haines
FUN = config_memoized ?
Hash.new do |h,k|
# complex calculate val
h[k] = val
end :
lambda do |k|
# complex calculate val
end
# later
x = FUN[y]
Nothing really fancy I guess but it's nice how seemingly these
integrate. (Now, is this another thread split?)
could'nt you just use the default_proc in a Hash?
irb(main):001:0> fun= Hash.new do |h,k|
irb(main):002:1* p 'calculations'
irb(main):003:1> h[k]= rand
irb(main):004:1> end
That is what is in the example above. However, he has the trinary operator in
his example. Depending on the value of config_memoized, one either gets a
hash with a default block, or a lambda, but in use both of them may appear to
be the same.
a = Hash.new {|h,k| h[k] = (k * 10000007) % 20}
b = lambda {|k| (k * 10000007) % 20}
a[5]
=> 15
b[5]
=> 15
In the original example, it illustrated how, because lambdas implement #[],
one could have either a memoizing or a nonmeoizing FUN[] depending on a
configuration value.
Kind of neat,
Kirk Haines