如何使用inject重写代码段

时间:2014-11-13 05:54:25

标签: ruby

我认为变量lst重复了很多次,

我想用inject注入代码片段

我替换了

    lst = []
    settings.each do | value_pair|

settings.inject([]) do |lst, value_pair|

但是我遇到了一些错误,似乎没有相应的错误?

  def get_hash(settings)
    lst = []
    settings.each do | value_pair|
      begin
        key,v = value_pair[0], value_pair[1] # ["quant", "3"]
        case key
        when "codec"
          lst << {"codec" => v}
        else
          lst.last[key] = v
        end
      rescue Exception => e
        p e
      end
    end
    return lst
  end

使用注入版本重写

  def get_hash(settings)
    lst =  settings.inject([]) do | lst, value_pair|
      begin
        key,v = value_pair[0], value_pair[1] # ["quant", "3"]
        case key
        when "codec"
          lst << {"codec" => v}
        else
          lst.last[key] = v
        end
      rescue Exception => e
        p e
      end
    end
    return lst
  end

错误

    #<IndexError: string not matched>
#<NoMethodError: undefined method `last' for #<IndexError: string not matched>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77b4768>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77b4538>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77b41f0>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77afd08>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77af808>>
#<NoMethodError: undefined method `<<' for #<NoMethodError:0x007ffcb77af150>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77ae9f8>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77ae228>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77ad968>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77acc70>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77a7d60>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77a71d0>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77a6438>>
#<NoMethodError: undefined method `last' for #<NoMethodError:0x007ffcb77a56c8>>

2 个答案:

答案 0 :(得分:1)

这是等效的注入语句:

 def get_hash(settings)
    result = settings.inject([]) do |lst, value_pair|
      begin
        key,v = value_pair[0], value_pair[1] # ["quant", "3"]
        case key
        when "codec"
          lst << {"codec" => v}
        else
          lst.last[key] = v
        end
      rescue Exception => e
        p e
      end
      lst # << RETURN lst in the end of inject block
    end
    return result
  end

您必须在注入块的末尾返回聚合对象。

答案 1 :(得分:0)

我认为唯一会引发异常的是lst在行lst.last[key] = v执行时为空。如果这不正确,请告诉我。你没有包含一些数据用于测试,这太糟糕了。

def get_hash(settings)
  settings.inject([]) do |lst, (key, v)|
    if key == "codec"
      lst << {"codec" => v}
    else
      if lst.empty?
        p "'#{lst.last} = #{v}' was attempted when lst = []"
      else
        lst.last[key] = v
      end
    end
    lst
  end
end