oinak
9/15/2015 - 4:48 PM

Meditation on ruby hashes with procs as "dinamic conditions" for keys

Meditation on ruby hashes with procs as "dinamic conditions" for keys

>> h = {true => '1 is odd', false => '1 is even'}
=> {true=>"1 is odd", false=>"1 is even"}
>> h[true]
=> "1 is odd"

>> h = {1.odd? => '1 is odd', 1.even? => '1 is even'}
=> {true=>"1 is odd", false=>"1 is even"}
>> h[true]
=> "1 is odd"

>> p=1; h = {p.odd? => "#{p} is odd", p.even? => "#{p} is even"}
=> {true=>"1 is odd", false=>"1 is even"}
>> h[true]
=> "1 is odd"

>> p=0; h = {p.odd? => "#{p} is odd", p.even? => "#{p} is even"}
=> {false=>"0 is odd", true=>"0 is even"}
>> h[true]
=> "0 is even"

>> p=1; h={ -> { p.odd? }[] => 'odd', -> { p.even? }[] => 'even' }
=> {true=>"odd", false=>"even"}
>> h[true]
=> "odd"

>> p=0; h={ -> { p.odd? }[] => 'odd', -> { p.even? }[] => 'even' }
=> {false=>"odd", true=>"even"}
>> h[true]
=> "even"

>> f = -> (p) { { -> { p.odd? }[] => 'odd', -> { p.even? }[] => 'even' }[true] }
=> #<Proc:0x00000002052bf0@(irb):49 (lambda)>
>> f[1]
=> "odd"
>> f[0]
=> "even"

# alternative/better? readability (minimum ambiguity)
>> f = proc do |p|
  Hash.new.merge(
    proc { p.odd?  }.call => 'odd',
    proc { p.even? }.call => 'even'
  ).fetch(true)
end
=> #<Proc:0x00000001fac070@(irb):52 (lambda)>
>> f[1]
=> "odd"