From: Josh Cheek Date: 2011-05-28T07:24:28+09:00 Subject: Re: Read symbols from external file --90e6ba53b090710a2c04a44966ff Content-Type: text/plain; charset=ISO-8859-1 On Fri, May 27, 2011 at 7:24 AM, Agent Mulder wrote: > =begin > Hello, > > I parse an array of symbols to output some program code. In reality I > map ALT, CTRL and SHIFT declarations to VK_KEYS in Java. But the > principle is the same. It is not a hash, a :symbol_* can appear more > than once. > > The list of symbols and what it applies to (ie SHIFT + VK_HOME) is a > straight array that I slice() in pairs just before I use it. It is > declared right on top of the little program below. > > I want to read in these ruby symbols from an external file > "zoo.txt",but I don't know how. Nor do I know how to write > file zoo.txt. > > Can you help me with this? > =end > > [ > :symbol_1,:Zebra, > :symbol_1,:Tiger, > :symbol_2,:Pinquin, > :symbol_2,:Flamingo, > :symbol_3,:Black_Widow, > ]. > each_slice(2).each do|b| > case b[0] > when:symbol_0 then puts <<_ > > Symbol Zero: #{b[0]}-> #{b[1]} > _ > when:symbol_1 then puts <<_ > > Symbol One: #{b[0]}-> #{b[1]} > _ > when:symbol_2 then puts <<_ > > Symbol Two: #{b[0]}-> #{b[1]} > _ > when:symbol_3 then puts <<_ > > Symbol Three: #{b[0]}-> #{b[1]} > _ > end > end > > -- > Posted via http://www.ruby-forum.com/. > > # I think parsing the file is the wrong approach. # I'd just use a real data format like YAML. # (I'd probably also not store these as arrays, # they look like good candidates for hashes or # structs, because remembering what position 0 is, # and what position 1 is will become a headache) require 'yaml' file = DATA symbols = YAML.load file symbols.each do |b| case b[0] when :symbol_0 then puts "Symbol Zero: #{b[0]} -> #{b[1]}" when :symbol_1 then puts "Symbol One: #{b[0]} -> #{b[1]}" when :symbol_2 then puts "Symbol Two: #{b[0]} -> #{b[1]}" when :symbol_3 then puts "Symbol Three: #{b[0]} -> #{b[1]}" end end __END__ --- - - :symbol_1 - :Zebra - - :symbol_1 - :Tiger - - :symbol_2 - :Pinquin - - :symbol_2 - :Flamingo - - :symbol_3 - :Black_Widow --90e6ba53b090710a2c04a44966ff--