在Ruby中使用注入?

我有一个名为Hsh的类,它基本上模拟了一个哈希。 它有一个Couple对象数组(其中包含名为one和two的字段,一个是另一个int,另一个是int的字符串名称)。

我应该能够接受以下电话:

h = x.inject({}) {|a, b| a[b.one] = b.two; a} 

其中x是Hsh对象。

我不知道如何在Hsh中实现inject方法? 比如,我会写什么:

 def inject ???? ?? ?? end 

它应该做的就是创建一个哈希映射。

 require 'ostruct' class Hsh include Enumerable def initialize @arr = (0..9).map{ |i| OpenStruct.new(:one => i, :two => "#{i}")} end def each(&block) @arr.each(&block) end end p Hsh.new.inject({}) {|a, b| a[b.one] = b.two; a} #=> {5=>"5", 0=>"0", 6=>"6", 1=>"1", 7=>"7", 2=>"2", 8=>"8", 3=>"3", 9=>"9", 4=>"4"} 

在这种特殊情况下, Hsh实际上是一个数组,所以除非你将它用于其他东西,否则这样复杂的代码没有意义,它可以更容易地完成:

 p (0..9).map{ |i| OpenStruct.new(:one => i, :two => "#{i}")} \ .inject({}) {|a, b| a[b.one] = b.two; a} #=> {5=>"5", 0=>"0", 6=>"6", 1=>"1", 7=>"7", 2=>"2", 8=>"8", 3=>"3", 9=>"9", 4=>"4"} 

你不应该真的需要实现它,只需实现Hsh#each并包含Enumerable ,你就可以免费inject

对于您的具体示例,这样的事情应该有效:

 def inject accumulator #I assume Hsh has some way to iterate over the elements each do |elem| accumulator = yield accumulator, elem end accumulator end 

但是注入的真实实现有点不同(例如,在没有提供累加器的情况下工作,采用符号而不是块等)

我使用OpenStruct而不是类。 看看这是否适合你

 require 'ostruct' class Hsh attr_accessor :arr def initialize obj = OpenStruct.new obj.one = 1 obj.two = "two" @arr = [obj] end def inject(hash) @arr.each do |arr| yield hash, arr end hash end end x = Hsh.new p x.inject({}) {|a, b| a[b.one] = b.two} #prints {1 => "two"}