How to implement injection in Ruby?

2019-03-07 02:13发布

问题:

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.

回答1:

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