且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

最有效的方式来格式化数据的散列?

更新时间:2023-11-25 15:10:58

这里有一个想法,非常类似于你所说的。您可能只需要为不想格式化的字段设置身份识别功能

  def pass(x)
x
end
$ b method_hash = {:date => method(:your_format_date)}
method_hash.default = method(:pass)

x = { :date => 3月5日,:时间=> 05:22:21,:first_name => John,:middle_initial => JJ}
x.reduce({}){| hsh,k | hsh [k [0]] = method_hash [k [0]]。call(k [1]); hsh}


I am using this array of hashes to do a batch insert into a mongo DB. Each hash was populated by parsing a text file so the formatting of fields are in an unpredictable format. It might look something like:

{date => "March 5", time => "05:22:21", first_name = "John", middle_initial = "JJ", ...}

And I would have a series of formatting functions. So maybe:

def format_date
..convert if needed..
end

def format_time
...
end

How would I go about calling the formatting functions on various records? I could see doing some kind of lambda call where I iterate through the hash and call a format_record_name function, but not all records will have formatting functions. For instance above the first_name record wouldn't need one. Any ideas?

Here's one idea, pretty similar to what you stated. You might just have an identity function for the fields you don't want to format

def pass(x)
   x
end 

method_hash = {:date=>method(:your_format_date)}
method_hash.default = method(:pass)

x = {:date => "March 5", :time => "05:22:21", :first_name => "John", :middle_initial => "JJ"}
x.reduce({}) { |hsh,k|  hsh[k[0]] = method_hash[k[0]].call(k[1]); hsh }