格式化数据哈希的最有效方法?
我正在使用这个哈希数组将批量插入到 mongo DB 中。每个散列都是通过解析文本文件来填充的,因此字段的格式是不可预测的格式。它可能看起来像:
{date => "March 5", time => "05:22:21", first_name = "John", middle_initial = "JJ", ...}
我会有一系列格式化函数。那么也许:
def format_date
..convert if needed..
end
def format_time
...
end
我将如何调用各种记录的格式化函数?我可以看到进行某种 lambda 调用,在其中迭代哈希并调用 format_record_name 函数,但并非所有记录都具有格式化函数。例如上面的first_name记录就不需要一个。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需保留您想要处理的键的列表即可。您甚至可以使用哈希将其与转换函数联系起来:
Just keep a list of the keys that you do want to handle. You could even tie it to the transformation functions with a Hash:
这是一个想法,与您所说的非常相似。您可能只有一个用于不想格式化的字段的标识函数
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
利用 Ruby 的 Singleton(或 Eigen)类,然后下面的代码可以解决您的问题:
Make use of Ruby's Singleton (or Eigen) class and then the following one liner solves your problem: