最有效的方式来格式化数据的散列? [英] Most efficient way to format a hash of data?

查看:128
本文介绍了最有效的方式来格式化数据的散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个哈希数组来做一个批量插入到mongo数据库。每个散列都是通过解析文本文件来填充的,所以字段的格式是不可预知的格式。它可能看起来像这样:

  {date => 3月5日,时间=> 05:22:21,first_name =John,middle_initial =JJ,...} 



我会有一系列的格式化功能。所以也许:

  def format_date 
.convert if if needed ..
end

def format_time
...
end

我该怎么去关于在各种记录上调用格式化函数?我可以看到做了一些lambda调用,在迭代散列并调用format_record_name函数,但不是所有记录都具有格式化函数。例如,first_name记录上面不需要一个。任何想法?

解决方案

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

  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 }

这篇关于最有效的方式来格式化数据的散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆