Currying
Often I make a class to just manage a Hash or Hash / Struct combo.
I was thinking: why not just add the methods I need to the object?
H = {}.tap { it.instance_exec {
@add = proc {|k, *v| self[k] = (v.one? ? v.first : v) }
def method_missing(k, *v) = ( self.key?(k) ? self[k] : @add.curry(2)[k] )
}}
H.apa[3,11]
p H.apa # => [3, 11]
H.hula['hula']
H.dance[proc {|n| n.times {print H.hula}; puts }]
H.dance[2] # => hulahula
NOTE: Array#one? is not the same as Array#size == 1.. but counts instead ’truthy elements’. So [nil, 0].one?
is true. It also takes an argument and a block:
%w(olle pelle kalle).one?('pelle') # => true
%w(pelle olle pelle kalle).one?('pelle') # => false
%w(olle pelle kalle anna).one? { it.endwith?('a') } # => true
%w(pia olle pelle kalle anna).one? { it.endwith?('a') } # => false