最有效的方式来格式化数据的散列? [英] Most efficient way to format a hash of data?
问题描述
{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屋!