ruby - how to rewrite the snippet with inject -
i think variable lst
repeating many times,
i want write snippet inject
i replaced
lst = [] settings.each | value_pair|
with
settings.inject([]) |lst, value_pair|
but got errors, seems there not equivalent ?
code def get_hash(settings) lst = [] settings.each | 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 homecoming lst end
rewrite inject version def get_hash(settings) lst = settings.inject([]) | 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 homecoming lst end
errors #<indexerror: string not matched> #<nomethoderror: undefined method `last' #<indexerror: string not matched>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77b4768>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77b4538>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77b41f0>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77afd08>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77af808>> #<nomethoderror: undefined method `<<' #<nomethoderror:0x007ffcb77af150>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77ae9f8>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77ae228>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77ad968>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77acc70>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77a7d60>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77a71d0>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77a6438>> #<nomethoderror: undefined method `last' #<nomethoderror:0x007ffcb77a56c8>>
this equivalent inject statement:
def get_hash(settings) result = settings.inject([]) |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 # << homecoming lst in end of inject block end homecoming result end
you have homecoming aggregated object in end of inject block.
ruby
No comments:
Post a Comment