Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.ruby Subject: Re: extract into a method - struggling to abstract Date: Tue, 5 Jul 2016 23:21:55 +0200 Lines: 56 Message-ID: References: <1ce04734-30d5-47d8-afaf-ae31d2537756@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net GWUg0/yrPcEj+TOwmQ3psgFAjJ31GTsD657j6fQm7YyrEVAeI= Cancel-Lock: sha1:tuM2Y+qHj1PpQyFGlFpT3uUBYqY= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Thunderbird/38.8.0 In-Reply-To: <1ce04734-30d5-47d8-afaf-ae31d2537756@googlegroups.com> Xref: csiph.com comp.lang.ruby:7275 On 04.07.2016 13:27, Sayth Renshaw wrote: > This is close. > However not all values are integers, some are strings. > > Can you make templates that you can drop into the function? Just a rough idea data = { 'number' => :to_i, 'id' => :to_i, 'horse' => nil, 'age' => :to_i, 'sex' => :to_s, 'colour' => lambda {|x| "Color #{x}"}, } def extract_value(path_id, data) @doc.search('race').map do |race| puts path_id extracted_data = race.search(path_id).map do |node| {}.tap do |hash| data.each {|d, m| val = node[d] hash[d.to_sym] = m ? m.to_proc[val] : val) } end end values = { race['id'].to_i => extracted_data } ap values # next line will prematurely return from the method, # do you want that? return values end end There is room for optimization, i.e. avoiding repeated to_proc calls. > PS I learnt tap from your previous post I had thought it was a typo of map but no http://ruby-doc.org/core-2.3.1/Object.html#method-i-tap :-) :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/