Ruby:在块中重用值而不将其赋值给变量(动态写入对象方法)

在某些情况下,我想将块应用于某个值并使用此块内的值,以将枚举器编码样式用于每个元素。

如果这种方法被称为decompose ,它看起来像:

 result = [3, 4, 7, 8].decompose{ |array| array[2] + array[3] } # result = 15 # OR result = {:key1 => 'value', :key2 => true}.decompose{ |hash| hash[:key1] if hash[:key2] } # result = 'value' # OR [min, max] = [3, 4, 7, 8].decompose{ |array| [array.min, array.max] } # [min, max] = [3, 8] # OR result = 100.decompose{ |int| (int - 1) * (int + 1) / (int * int) } # result = 1 # OR result = 'Paris'.decompose{ |str| str.replace('a', '') + str[0] } # result = 'PrisP' 

该方法简单地为块生成self ,返回块的结果。 我不认为它存在,但你可以自己实现它:

 class Object def decompose yield self end end [3, 4, 7, 8].decompose{ |array| array[2] + array[3] } #=> 15 {:key1 => 'value', :key2 => true}.decompose{ |hash| hash[:key1] if hash[:key2] } #=> "value" [3, 4, 7, 8].decompose{ |array| [array.min, array.max] } #=> [3, 8] 

它确实存在(我不相信它没有)。

它被称为BasicObject#instance_eval 。 这是doc: http : //apidock.com/ruby/BasicObject/instance_eval

自Ruby 1.9以来可用,正如这篇文章所解释的: Ruby中的Object和BasicObject有什么区别?