开发者

Storing cvs data for further manipulation using Ruby

开发者 https://www.devze.com 2022-12-31 17:39 出处:网络
I am dealing with a csv file that has some customer information (email, name, address, amount, [shopping_list: item 1, item 2]).

I am dealing with a csv file that has some customer information (email, name, address, amount, [shopping_list: item 1, item 2]).

I would like work with the data and produce some labels for printing... as well as to gather some extra information (total amounts, total items 1...)

My main concern is to find the appropriate structure to store the data in ruby for future manipulation. For now I have thought about the following possibilities:

  1. multidimensional arrays: pretty simple to build, but pretty hard to access the data in a beautiful ruby way.

  2. hashes: having the email as key, and storing the information in different hashes (one hash for name, another hash for address, another hash for shopping list...)

  3. (getting the cvs data in to a Database and working with the data from ruby??)

I would really appreciate y开发者_如何学JAVAour advice and guidance!!


Once you have more than a couple pieces of information that you need to group together, it's time to consider moving from a generic hash/array to something more specialized. A good candidate for what you've described is Ruby's struct module:

Customer = Struct.new(:email, :name, :address) # etc.

bill = Customer.new('bill@asdf.com', 'Bill Foo', '123 Bar St.')

puts "#{bill.name} lives at #{bill.address} and can be reached at #{bill.email}"

Output:

Bill Foo lives at 123 Bar St. and can be reached at bill@asdf.com

Struct#new simply creates a class with an attr_accessor for each symbol you pass in. Well, it actually creates a bit more than that, but for starters, that's all you need to worry about.

Once you've got the data from each row packed into an object of some sort (whether it's a struct or a class of your own), then you can worry about how to store those objects.

  • A hash will be ideal for random access by a given key (perhaps the customer's name or other unique ID)
  • A one-dimensional array works fine for iterating over the entire set of customers in the same order they were inserted
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号