How to implement injection in Ruby?

前端 未结 1 1670
醉酒成梦
醉酒成梦 2021-01-29 11:28

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 t

相关标签:
1条回答
  • 2021-01-29 11:54

    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

    0 讨论(0)
提交回复
热议问题