本文介绍了在Ruby中使用注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class called Hsh which basically simulates a hash. It has an array of Couple objects (which hold fields named one and two, one is an int another is a string name of that int).

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

I am supposed to be able to accept the following call:

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

其中x是Hsh对象。

我不确定如何在Hsh中实现注入方法?像,我会写什么:

I am not sure how to implement the inject method within Hsh? Like, what would I write in:

def inject ????
??
??
end

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

All it's supposed to do is create a hash map.

推荐答案

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 实际上是一个数组,所以除非您将它用于别的东西,这样复杂的代码没有意义,它可以做得更容易:

In this particular case Hsh is actually an array, so unless you use it for something else such a complex code doesn't make sense, it can be done much easier:

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"}

这篇关于在Ruby中使用注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 07:06