ruby 关于红宝石的冥想哈希与触发器作为键的“dinamic条件”
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 关于红宝石的冥想哈希与触发器作为键的“dinamic条件”相关的知识,希望对你有一定的参考价值。
>> 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"
以上是关于ruby 关于红宝石的冥想哈希与触发器作为键的“dinamic条件”的主要内容,如果未能解决你的问题,请参考以下文章
如何将带有对象作为键的 Ruby 哈希对象作为 Map 对象发送到前端 Javascript
对日期为键的哈希进行排序。 (红宝石1.8.7)
ruby 关于服务缓存的冥想,带有一个示例stroage类
哈希键的Ruby值?
如何在 Ruby 中复制哈希?
在 Ruby 中更新哈希键的惯用方法是啥?