tags:

views:

27

answers:

1

Hey everyone. Trying to take a simple test.txt file and seperate the text and integers after its read in for array manipulation. The idea is to be able to use/require the attr_accessor from the seperate Person class. So I can use :name, :hair_color, :gender

For example lets says we have in our text file which is all seperated by the tab delimiter, for shortness I just used space:

Bob red_hair 38
Joe brown_hair 39
John black_hair 40

My class would read something like:

 class Person
    attr_accessor :name, :hair_color, :gender


   def initialize
    @place_holder = 'test'
   end

   def to_s
    @test_string = 'test a string'
   end
 end

My main file that I'm having strategy issues with so far:

 test_my_array = File.readlines('test.txt').each('\t')  #having trouble with 

I'm pretty sure its easier to manipulate line by line rather then one file. I'm not sure where to go after that. I know I need to seperate my data some how for :name, :hair_color, :gender. Throw some code up so I can try things out.

Thanks for the help!

+1  A: 

If you make your initialize method accept values for name, hair_color and gender, you can do it like this:

my_array = File.readlines('test.txt').map do |line|
  Person.new( *line.split("\t") )
end

If you can't modify your initialize method, you'll need to call the writer methods one by one like this:

my_array = File.readlines('test.txt').map do |line|
  name, hair_color, gender = line.split("\t")
  person = Person.new
  person.name = name
  person.hair_color = hair_color
  person.gender = gender
  person
end

The easiest way to make initialize accept the attributes as argument without having to set all the variables yourself, is to use Struct, which shortens your entire code to:

Person = Struct.new(:name, :hair_color, :gender)
my_array = File.readlines('test.txt').map do |line|
  Person.new( *line.split("\t") )
end
#=> [ #<struct Person name="Bob", hair_color="red_hair", gender="male\n">,
#     #<struct Person name="Joe", hair_color="brown_hair", gender="male\n">,
#     #<struct Person name="John", hair_color="black_hair", gender="male\n">,
#     #<struct Person name="\n", hair_color=nil, gender=nil>]
sepp2k
I forgot about .map, doh! Thanks for the help!
Matt