如何在Ruby中实现注入? [英] How to implement injection in Ruby?
本文介绍了如何在Ruby中实现注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
h = x.inject({}){| a, C | a [b.one] = b.two; a}
其中x是Couple对象的序列(它们只包含两个数字字段,一个和两个)。
我不确定如何在Couple中实现注入方法。 在中定义一个
,然后在其中包含 #each
夫妻 Enumerable
。
class Couple
def each
yielda
yieldb
end
include Enumerable
end
couple = Couple.new
couple.inject(){| str,obj | str + obj}
#=> ab
http://www.ruby-doc.org/core-1.9.3/Enumerable.html
I need to be able to use this call:
h = x.inject({}) {|a, b| a[b.one] = b.two; a}
Where x is a sequence of Couple objects (these just contain two number fields, one and two).
I am not sure how to implement the inject method in Couple.
解决方案
Define an #each
method in Couple
, then include Enumerable
in it.
class Couple
def each
yield "a"
yield "b"
end
include Enumerable
end
couple = Couple.new
couple.inject("") { |str, obj| str + obj }
# => "ab"
http://www.ruby-doc.org/core-1.9.3/Enumerable.html
这篇关于如何在Ruby中实现注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文