From: Josh Cheek Date: 2011-01-14T07:58:43+09:00 Subject: Re: Retrieving and copying element from array --001485f7d33cce4f5e0499c24178 Content-Type: text/plain; charset=ISO-8859-1 On Thu, Jan 13, 2011 at 2:19 PM, Simon Harrison wrote: > Thanks for reply, Anurag. Can't get this to work though: > > irb(main):001:0> lines = File.readlines('test.txt') > => ["category: cat1\n", " item1\n", " item2\n", " item3\n", "category: > cat2\n", " item1\n", "category: cat3\n", " item1\n", " item2\n", " > item3\n", " item4\n", "\n"] > irb(main):002:0> puts lines > category: cat1 > item1 > item2 > item3 > category: cat2 > item1 > category: cat3 > item1 > item2 > item3 > item4 > > => nil > irb(main):003:0> result = [] > => [] > irb(main):004:0> lines.each_slice(2) { |i, j| > result.push(i.sub(/category: /, '')); b.push(*j.split(', '))} > NameError: undefined local variable or method `b' for main:Object > from (irb):4:in `block in irb_binding' > from (irb):4:in `each' > from (irb):4:in `each_slice' > from (irb):4 > from /usr/local/bin/irb:12:in `
' > irb(main):005:0> lines.each_slice(2) { |i, j| > result.push(i.sub(/category: /, '')); j.push(*j.split(', '))} > NoMethodError: undefined method `push' for " item1\n":String > from (irb):5:in `block in irb_binding' > from (irb):5:in `each' > from (irb):5:in `each_slice' > from (irb):5 > from /usr/local/bin/irb:12:in `
' > > -- > Posted via http://www.ruby-forum.com/. > > I recommend you don't store your data like this, it is fragile and error prone. You can see your data already does not look like you have said in your first post, each item in cat1 is its own line (ie index 1 in your first post is "item1, item2, item3" but in your actual data, it is "item1\n", so even after you fix the part where he said b.push instead of result.push, it will still be wrong. I recommend using a real data format such as yaml, xml, or json. It's actually much easier to get started with this than you think, you can just build the data in memory how you want it to look, then tell YAML to convert it, and store it in a file. Ta-da, a valid YAML representation of your data. Here is an example with this data https://gist.github.com/778772 It is slightly different in that I read them into hashes, because I dislike storing category and items in the same array -- if it were me, I might even go a step further and store them in a struct instead of a hash. --001485f7d33cce4f5e0499c24178--